ts-mailcow-api
Version:
TypeScript wrapper for the mailcow API.
88 lines • 3.13 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
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))));
});
}
/**
* Factory method patterns for creating Axios Requests.
* @internal
*/
class RequestFactory {
constructor(ctx) {
this.ctx = ctx;
}
/**
* 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 __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
axios_1.default
.post(this.ctx.BASE_URL + route, payload, this.ctx.AXIOS_CONFIG)
// On succes
.then((res) => {
resolve(res.data);
})
// On error
.catch((e) => {
const { msg } = e.response.data;
reject(new types_1.MailcowException(msg));
});
});
});
}
/**
* GET Request Factory
* @param route - The route to which to send the request.
*/
get(route) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
axios_1.default
.get(this.ctx.BASE_URL + route, this.ctx.AXIOS_CONFIG)
// On succes
.then((res) => {
resolve(res.data);
})
// On error
.catch((e) => {
const { msg } = e.response.data;
reject(new types_1.MailcowException(msg));
});
});
});
}
}
exports.default = RequestFactory;
//# sourceMappingURL=request-factory.js.map