UNPKG

@klevu/core

Version:

Typescript SDK that simplifies development on Klevu backend. Klevu provides advanced AI-powered search and discovery solutions for online retailers.

51 lines (50 loc) 1.58 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.KlevuFetchCache = void 0; const config_js_1 = require("../config.js"); const isBrowser_js_1 = require("../utils/isBrowser.js"); /** * @ignore */ class KlevuFetchCache { constructor() { this._cache = new Map(); this._timestamp = new Map(); } /** * checks if cache has value and returns it * * @param key * @param force For testing purposes * @returns undefined if not cached */ check(key, force = false) { // never cache on node server if (!force && !(0, isBrowser_js_1.isBrowser)()) { return undefined; } const hash = this.hash(key); if (!this._cache.has(hash)) { return undefined; } const cached = this._cache.get(hash); const ts = this._timestamp.get(hash); if (cached && ts) { if (new Date().getTime() < ts) { return JSON.parse(cached); } this._cache.delete(hash); this._timestamp.delete(hash); } return undefined; } cache(key, data, timetocache = config_js_1.KlevuConfig.getDefault().cacheMaxTTL) { const hash = this.hash(key); this._cache.set(hash, JSON.stringify(data)); this._timestamp.set(hash, new Date().getTime() + timetocache); } hash(input) { return Array.from(JSON.stringify(input)).reduce((s, c) => (Math.imul(31, s) + c.charCodeAt(0)) | 0, 0); } } exports.KlevuFetchCache = KlevuFetchCache;