UNPKG

@batlify/mscms2-api

Version:

MineStoreCMS v3 API package

63 lines (62 loc) 2.29 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); const dotenv_1 = __importDefault(require("dotenv")); const universal_cookie_1 = __importDefault(require("universal-cookie")); dotenv_1.default.config(); class Context { constructor() { this.cookies = new universal_cookie_1.default(); this.apiUrl = process.env.NEXT_PUBLIC_API_URL || ''; } /* * Send request to your MineStoreCMS instance * @param authorize If it's true, uses Authorization header with token * @param method HTTP method (GET, POST, PUT, DELETE, PATCH) * @param url API endpoint (will be appended to apiUrl [https://store.domain.com/api/:your-endpoint]) * @param body Request body * @returns Response data * @throws Error (e.g. 401 Unauthorized) */ async request(authorize = false, method, url, body = {}) { var _a; const headers = { 'Content-Type': 'application/json', }; if (authorize) { const token = this.cookies.get('mscms_auth_token'); if (token) { headers['Authorization'] = `Bearer ${token}`; } else { return { code: 401, message: 'Unauthorized - need to be logged in' }; } } try { const response = await (0, axios_1.default)({ method, url: `${this.apiUrl}/api${url}`, data: body, headers, withCredentials: true, }); return response.data; } catch (error) { throw ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) || new Error('An unknown error occurred'); } } setCookie(key, value, maxAge = 60 * 60 * 24 * 7) { this.cookies.set(key, value, { path: '/', httpOnly: process.env.PETR_HTTP === 'true', secure: process.env.PETR_SECURE === 'true', sameSite: 'lax', maxAge: maxAge, }); } } exports.default = Context;