UNPKG

@chmoyle-conga/graphql-cart

Version:

Cart module for realtime subscriptions to conga cart

61 lines (60 loc) 2.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const jwt_decode_1 = require("jwt-decode"); class Environment { constructor() { } initialize(_environment) { this.environment = _environment; } validateStorageKey(keyValue) { // parse the JSON data from the keyValue if (!keyValue) return null; try { const data = JSON.parse(keyValue || ''); const authToken = (data.authzData || data.access_token); if (authToken) { // check if the token is expired const decodedToken = (0, jwt_decode_1.jwtDecode)(authToken); if (decodedToken.exp && decodedToken.exp < Date.now() / 1000) { return null; } else { return authToken; } } } catch (e) { // ignore } return null; } getToken() { if (!this.environment) throw new Error("Environment not initialized"); let value; // Get the session storage json data that matches the pattern number-clientId let key = Object.keys(localStorage).find(key => { var _a; return key === null || key === void 0 ? void 0 : key.endsWith(((_a = this.environment) === null || _a === void 0 ? void 0 : _a.clientId) || ''); }); if (key) { value = this.validateStorageKey(localStorage.getItem(key || '')); } if (!value) { key = Object.keys(sessionStorage).find(key => { var _a; return key === null || key === void 0 ? void 0 : key.endsWith(((_a = this.environment) === null || _a === void 0 ? void 0 : _a.clientId) || ''); }); value = this.validateStorageKey(sessionStorage.getItem(key || '')); } return value; } getEndpoint() { var _a; if (!this.environment) throw new Error("Environment not initialized"); let endpoint = (_a = this.environment) === null || _a === void 0 ? void 0 : _a.endpoint; // If it ends with a slash, remove it if (endpoint === null || endpoint === void 0 ? void 0 : endpoint.endsWith("/")) { endpoint = endpoint.slice(0, -1); } return endpoint; } } const environment = new Environment(); exports.default = environment;