UNPKG

mailersend

Version:

Node.js helper module for MailerSend API

79 lines (78 loc) 3.2 kB
"use strict"; 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.RequestService = void 0; const gaxios_1 = require("gaxios"); var qs = require('qs'); class RequestService { constructor(apiKey, baseUrl) { this.apiKey = apiKey; this.baseUrl = baseUrl; } normalizeHeaders(headers) { if (headers instanceof Headers) { return Object.fromEntries(headers.entries()); } return headers; } post(path, data) { return __awaiter(this, void 0, void 0, function* () { return this.request("POST", path, data); }); } get(path, queryParams) { return __awaiter(this, void 0, void 0, function* () { return this.request("GET", path, null, queryParams); }); } deleteReq(path, data) { return __awaiter(this, void 0, void 0, function* () { return this.request("DELETE", path, data); }); } put(path, data) { return __awaiter(this, void 0, void 0, function* () { return this.request("PUT", path, data); }); } request(method, path, body, queryParams) { return __awaiter(this, void 0, void 0, function* () { try { const requestParams = { url: path.replace(/^\//, ''), baseURL: this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/', method, headers: { Authorization: `Bearer ${this.apiKey}` }, responseType: "json", fetchImplementation: globalThis.fetch, }; if (body) { requestParams.data = body; } if (queryParams) { requestParams.params = new URLSearchParams(qs.stringify(queryParams)); } const { headers, data, status } = yield (0, gaxios_1.request)(requestParams); return { headers: this.normalizeHeaders(headers), body: data, statusCode: status }; } catch (e) { if (e === null || e === void 0 ? void 0 : e.response) { const { headers, data, status } = e.response; throw { headers: this.normalizeHeaders(headers), body: data, statusCode: status }; } else { throw e; } } }); } } exports.RequestService = RequestService;