UNPKG

@sap-cloud-sdk/connectivity

Version:

SAP Cloud SDK for JavaScript connectivity

69 lines 2.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cache = void 0; /** * Representation of a cache to transiently store objects locally for faster access. * @typeParam T - Type of the cache entries. * @internal */ class Cache { /** * Creates an instance of Cache. * @param defaultValidityTime - The default validity time in milliseconds. Use 0 for unlimited cache duration. */ constructor(defaultValidityTime) { this.defaultValidityTime = defaultValidityTime; this.cache = {}; } /** * Clear all cached items. */ clear() { this.cache = {}; } /** * Specifies whether an entry with a given key is defined in cache. * @param key - The entry's key. * @returns A boolean value that indicates whether the entry exists in cache. */ hasKey(key) { return this.cache.hasOwnProperty(key); } /** * Getter of cached entries. * @param key - The key of the entry to retrieve. * @returns The corresponding entry to the provided key if it is still valid, returns `undefined` otherwise. */ get(key) { return key && this.hasKey(key) && !isExpired(this.cache[key]) ? this.cache[key].entry : undefined; } /** * Setter of entries in cache. * @param key - The entry's key. * @param item - The entry to cache. */ set(key, item) { if (key) { const expires = item.expires ?? this.inferDefaultExpirationTime(); this.cache[key] = { entry: item.entry, expires }; } } inferDefaultExpirationTime() { const now = new Date(); return this.defaultValidityTime ? now .setMilliseconds(now.getMilliseconds() + this.defaultValidityTime) .valueOf() : undefined; } } exports.Cache = Cache; function isExpired(item) { if (item.expires === undefined) { return false; } return item.expires < Date.now(); } //# sourceMappingURL=cache.js.map