UNPKG

simple-in-memory-cache

Version:

A simple in-memory cache, for nodejs and the browser, with time based expiration policies.

37 lines 1.58 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createCache = void 0; const uni_time_1 = require("@ehmpathy/uni-time"); const getMseNow = () => new Date().getTime(); const createCache = ({ expiration: defaultExpiration, } = { expiration: { minutes: 5 } }) => { // initialize a fresh in-memory cache object const cache = {}; // define how to set an item into the cache const set = (key, value, { expiration = defaultExpiration, } = {}) => { // handle cache invalidation if (value === undefined) { delete cache[key]; return; } // handle setting const expiresAtMse = getMseNow() + (expiration ? (0, uni_time_1.toMilliseconds)(expiration) : Infinity); // infinity if null cache[key] = { value, expiresAtMse }; }; // define how to get an item from the cache const get = (key) => { const cacheContent = cache[key]; if (!cacheContent) return undefined; // if not in cache, then undefined if (cacheContent.expiresAtMse <= getMseNow()) return undefined; // if already expired, then undefined return cacheContent.value; // otherwise, its in the cache and not expired, so return the value }; // define how to grab all valid keys const keys = () => Object.entries(cache) .filter(([_, value]) => value.expiresAtMse > getMseNow()) .map(([key]) => key); // return the api return { set, get, keys }; }; exports.createCache = createCache; //# sourceMappingURL=cache.js.map