UNPKG

mpp-sdk

Version:

SDK to talk to the Memento Payments Platform

62 lines (61 loc) 2.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseEndpoint = void 0; const tslib_1 = require("tslib"); const errors_1 = require("../errors"); const result_1 = require("../types/result"); class BaseEndpoint { constructor(config) { this.config = config.config; this.http = config.http; this.sessions = config.sessions; } /** * Performs an http request using the provided axios config. * Auto refreshes session token if that setting is enabled and * wraps the response in a MPPResponse. * @param config axios request config */ doRequest(config) { var _a; return tslib_1.__awaiter(this, void 0, void 0, function* () { // Attempt to add session token if we have a valid auth token, otherwise // we don't add the session token and just let the api return an error. if (yield this.sessions.hasAuthToken()) { // Check if we should automatically renew session if (this.config.autoRefreshSession) { if (!this.sessions.hasSession) { try { yield this.sessions.renew(); } catch (e) { // Error is already handled so we rethrow if (e instanceof errors_1.MPPError) { throw e; } throw (0, errors_1.errorHandler)(e); } } } // Add auth header to config if (!config.headers) { config.headers = {}; } config.headers["Authorization"] = `Bearer ${this.sessions.token}`; } try { if (!((_a = config.url) === null || _a === void 0 ? void 0 : _a.startsWith(`/${this.config.version}`))) { config.url = `/${this.config.version}${config.url}`; } const result = yield this.http.request(config); return new result_1.MPPResult(result, // Pass in the request handler and bind it to the parent class this.doRequest.bind(this)); } catch (e) { throw (0, errors_1.errorHandler)(e); } }); } } exports.BaseEndpoint = BaseEndpoint;