UNPKG

@chmoyle-conga/graphql-cart

Version:

Cart module for realtime subscriptions to conga cart

67 lines (66 loc) 2.36 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) { if (!keyValue) return null; let authToken = null; // parse the JSON data from the keyValue try { const data = JSON.parse(keyValue || ''); authToken = (data.authzData || data.access_token); } catch (e) { console.log("Failed to parse JSON data:", keyValue); // If parsing fails, treat as raw token authToken = keyValue; } if (authToken) { // Decode the JWT token const decodedToken = (0, jwt_decode_1.jwtDecode)(authToken); // Check if the token is expired if (decodedToken.exp && decodedToken.exp * 1000 > Date.now()) { return authToken; } else { console.log("Token is expired"); } } return null; } getToken() { if (!this.environment) { throw new Error("Environment not initialized"); } const clientId = this.environment.clientId || ''; const storages = [sessionStorage, localStorage]; for (const storage of storages) { const key = Object.keys(storage).find(k => k === null || k === void 0 ? void 0 : k.endsWith(clientId)); if (key) { const token = this.validateStorageKey(storage.getItem(key)); if (token) { return token; } } } return null; } 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;