UNPKG

postmark

Version:

Official Node.js client library for the Postmark HTTP API - https://www.postmarkapp.com

258 lines 12.4 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FetchHttpClient = void 0; var models_1 = require("./models"); var index_1 = require("./errors/index"); /** * Http client implementation based on the native Fetch API (available in Node 18+). * This keeps the SDK dependency-free while preserving the previous error handling contract. */ var FetchHttpClient = /** @class */ (function (_super) { __extends(FetchHttpClient, _super); function FetchHttpClient(configOptions) { var _this = _super.call(this, configOptions) || this; _this.errorHandler = new index_1.ErrorHandler(); return _this; } /** * Create http client instance with default settings. */ FetchHttpClient.prototype.initHttpClient = function (configOptions) { var _a; this.clientOptions = __assign(__assign({}, models_1.HttpClient.DefaultOptions), configOptions); // Use a caller-supplied fetch when provided (e.g. bound to a proxy dispatcher), // otherwise wrap the global fetch. The reference is stored so it can also be stubbed in tests. this.client = (_a = this.clientOptions.fetch) !== null && _a !== void 0 ? _a : (function (input, init) { return fetch(input, init); }); }; /** * Process http request. * * @param method - Which type of http request will be executed. * @param path - API URL endpoint. * @param queryParameters - Querystring parameters used for http request. * @param body - Data sent with http request. * @param requestHeaders - Headers sent with http request. */ FetchHttpClient.prototype.httpRequest = function (method, path, queryParameters, body, requestHeaders) { return __awaiter(this, void 0, void 0, function () { var response, errorThrown_1, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.client(this.buildRequestURL(path, queryParameters), { method: method, headers: requestHeaders, body: (body === null || body === undefined) ? undefined : JSON.stringify(body), signal: this.buildTimeoutSignal(), })]; case 1: response = _a.sent(); return [3 /*break*/, 3]; case 2: errorThrown_1 = _a.sent(); // Network errors, aborts and timeouts reject the fetch promise. return [2 /*return*/, Promise.reject(this.transformError(errorThrown_1))]; case 3: return [4 /*yield*/, this.parseResponseBody(response)]; case 4: data = _a.sent(); // Unlike axios, fetch does not reject on non-2xx responses, so handle them manually. if (response.status >= 200 && response.status < 300) { return [2 /*return*/, data]; } return [2 /*return*/, Promise.reject(this.buildRequestError(data, response.status))]; } }); }); }; /** * Build the full request URL from the base URL, path and query parameters. * * @private */ FetchHttpClient.prototype.buildRequestURL = function (path, queryParameters) { var baseURL = this.getBaseHttpRequestURL(); var normalizedPath = path.startsWith("/") ? path : "/".concat(path); var queryString = this.serializeQueryParameters(queryParameters); return "".concat(baseURL).concat(normalizedPath).concat(queryString); }; /** * Serialize query parameters into a querystring, ignoring undefined and null values. * * Every current *FilteringParameters query value is a string, number, boolean or enum, so * primitive serialization is sufficient today. Arrays are still expanded to repeated keys and * Date values to ISO strings (as axios used to do) so that adding such a filter param later * cannot silently produce a malformed URL via String([1,2]) or String(new Date()). * * @private */ FetchHttpClient.prototype.serializeQueryParameters = function (queryParameters) { var _this = this; var searchParams = new URLSearchParams(); Object.entries(queryParameters || {}).forEach(function (_a) { var key = _a[0], value = _a[1]; if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach(function (item) { if (item !== undefined && item !== null) { searchParams.append(key, _this.stringifyQueryValue(item)); } }); } else { searchParams.append(key, _this.stringifyQueryValue(value)); } }); var queryString = searchParams.toString(); return queryString === "" ? "" : "?".concat(queryString); }; FetchHttpClient.prototype.stringifyQueryValue = function (value) { return (value instanceof Date) ? value.toISOString() : String(value); }; /** * Read and parse the response body. Postmark responses are JSON, but empty bodies are tolerated. * * @private */ FetchHttpClient.prototype.parseResponseBody = function (response) { return __awaiter(this, void 0, void 0, function () { var text; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, response.text()]; case 1: text = _a.sent(); if (text === "") { return [2 /*return*/, {}]; } try { return [2 /*return*/, JSON.parse(text)]; } catch (_b) { return [2 /*return*/, text]; } return [2 /*return*/]; } }); }); }; /** * Build a Postmark error from a non-2xx response. * * @param data - parsed response body. * @param status - http response status code. * * @return {PostmarkError} - formatted Postmark error * @private */ FetchHttpClient.prototype.buildRequestError = function (data, status) { var errorCode = this.adjustValue(0, data == null ? undefined : data.ErrorCode); var message = this.adjustValue("Request returned status code ".concat(status), data == null ? undefined : data.Message); return this.errorHandler.buildError(message, errorCode, status); }; /** * Transform a thrown error (network failure, timeout, abort) into a proper Postmark error. * * @param errorThrown - error thrown while performing the request. * * @return {PostmarkError} - formatted Postmark error * @private */ FetchHttpClient.prototype.transformError = function (errorThrown) { if (errorThrown !== null && errorThrown.message !== undefined) { return this.errorHandler.buildError(errorThrown.message); } return this.errorHandler.buildError(JSON.stringify(errorThrown, Object.getOwnPropertyNames(errorThrown))); }; /** * Build an AbortSignal that aborts the request once the configured timeout elapses. * * AbortSignal.timeout() is available at runtime in Node 18+, but is not present in the * lib.dom typings shipped with the TypeScript version this project pins, so it is * referenced through an explicit cast. * * @private */ FetchHttpClient.prototype.buildTimeoutSignal = function () { var abortSignal = AbortSignal; return abortSignal.timeout(this.getRequestTimeoutInMilliseconds()); }; /** * Timeout in seconds is adjusted to milliseconds. * * @private */ FetchHttpClient.prototype.getRequestTimeoutInMilliseconds = function () { return (this.clientOptions.timeout || 60) * 1000; }; FetchHttpClient.prototype.adjustValue = function (defaultValue, data) { return (data === undefined) ? defaultValue : data; }; return FetchHttpClient; }(models_1.HttpClient)); exports.FetchHttpClient = FetchHttpClient; //# sourceMappingURL=HttpClient.js.map