UNPKG

ts-mailcow-api

Version:
87 lines 2.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapPromiseToArray = wrapPromiseToArray; const axios_1 = require("axios"); const types_1 = require("./types"); /** * Ensures output is an array. * @param item * @internal */ function wrapToArray(item) { return Array.isArray(item) ? item : [item]; } /** * Function that wraps T | T[] to T[] * @internal * @param promise - The promise of which the output to wrap. */ function wrapPromiseToArray(promise) { return new Promise((resolve, reject) => { promise .then((res) => resolve(wrapToArray(res))) .catch((err) => reject(err instanceof Error ? err : new Error(String(err)))); }); } function isErrorType(type) { return type === 'danger' || type === 'error'; } /** * Checks if a Mailcow API response indicates an error. * Throws a MailcowException if a definite error is detected. */ function checkMailcowResponse(res) { const arr = Array.isArray(res) ? res : [res]; for (const item of arr) { if (isErrorType(item.type)) { throw new types_1.MailcowException(Array.isArray(item.msg) ? item.msg.join(', ') : item.msg); } } } /** * Factory method patterns for creating Axios Requests. * @internal */ class RequestFactory { ctx; constructor(ctx) { this.ctx = ctx; } /** * Executes a request and applies Mailcow-specific error handling: a 2XX * response with `type: 'danger'` or `type: 'error'` is converted into a * MailcowException, and an axios error whose response body looks like a * Mailcow error is unwrapped into a MailcowException as well. */ async request(send) { try { const res = await send(); checkMailcowResponse(res.data); return res.data; } catch (e) { if (axios_1.default.isAxiosError(e) && e.response?.data) { checkMailcowResponse(e.response.data); throw new types_1.MailcowException('Unknown Mailcow error'); } throw e; } } /** * POST Request Factory * @param route - The route to which to send the request. * @param payload - The payload to send with the request. */ post(route, payload) { return this.request(() => axios_1.default.post(this.ctx.BASE_URL + route, payload, this.ctx.AXIOS_CONFIG)); } /** * GET Request Factory * @param route - The route to which to send the request. */ get(route) { return this.request(() => axios_1.default.get(this.ctx.BASE_URL + route, this.ctx.AXIOS_CONFIG)); } } exports.default = RequestFactory; //# sourceMappingURL=request-factory.js.map