UNPKG

mpp-sdk

Version:

SDK to talk to the Memento Payments Platform

90 lines (89 loc) 3.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const errors_1 = require("../errors"); const axios_1 = tslib_1.__importDefault(require("axios")); class SessionsEndpoint { constructor(http, config, tokens) { this.http = http; this.config = config; this.tokens = tokens; this.renewingSessionPromise = null; this.session = null; } get hasSession() { return this.session != null && this.session.expires_at > new Date(); } get token() { var _a; return (_a = this.session) === null || _a === void 0 ? void 0 : _a.token; } hasAuthToken() { return this.tokens.hasAuthToken(); } renew() { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (this.renewingSessionPromise) { return this.renewingSessionPromise; } this.renewingSessionPromise = (() => tslib_1.__awaiter(this, void 0, void 0, function* () { try { const hasAuthToken = yield this.tokens.hasAuthToken(); if (!hasAuthToken) { throw new errors_1.AuthenticationError("No Authentication Token Provided"); } const { data } = yield this.create(); data.expires_at = new Date(data.expires_at); data.created_at = new Date(data.created_at); data.updated_at = new Date(data.updated_at); this.session = data; } catch (err) { throw err; } finally { this.renewingSessionPromise = null; } }))(); return this.renewingSessionPromise; }); } create() { return tslib_1.__awaiter(this, void 0, void 0, function* () { const authToken = yield this.config.storage.retrieveAuthToken(); if (!authToken) { throw new errors_1.AuthenticationError("No Authentication Token Provided"); } try { return yield this.http.post(`/${this.config.version}/sessions`, null, { auth: { username: authToken.token, password: "", }, }); } catch (err) { if (axios_1.default.isAxiosError(err) && err.response && err.response.status === 403) { throw new errors_1.LockedUserError(err.message, err.response.data); } throw (0, errors_1.errorHandler)(err); } }); } verify() { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { return this.http.get(`/${this.config.version}/sessions/verify`); } catch (err) { throw (0, errors_1.errorHandler)(err); } }); } clear() { this.session = null; } } exports.default = SessionsEndpoint;