@selfcommunity/utils
Version:
Utilities to integrate a Community.
124 lines (123 loc) • 3.04 kB
JavaScript
/**
* LruCache
*/
export class LruCache {
/**
* Initialize Cache
* @param maxEntries
*/
constructor(maxEntries = 10000) {
this.values = new Map();
this.maxEntries = maxEntries;
this.ssr = typeof window === 'undefined';
if (!this.ssr) {
window['__viewSCCache'] = this.values;
}
}
/**
* Get a key from the map store
* @param key
* @param value
* @param options
*/
get(key, value, options = { noSsr: true }) {
const hasKey = this.values.has(key);
let entry;
if (hasKey) {
// peek the entry, re-insert(updated if value) for LRU strategy
entry = this.values.get(key);
this.values.delete(key);
this.values.set(key, entry);
}
else if (value) {
// insert value if passed
entry = value;
!(this.ssr && options.noSsr) && this.values.set(key, entry);
}
return entry;
}
/**
* Set a key in the store
* @param key
* @param value
* @param options
*/
set(key, value, options = { noSsr: true }) {
if (this.ssr && options.noSsr) {
return;
}
if (this.values.size >= this.maxEntries) {
// least-recently used cache eviction strategy
const keyToDelete = this.values.keys().next().value;
this.values.delete(keyToDelete);
}
this.values.set(key, value);
}
/**
* Check if key is in cache
* @param key
*/
hasKey(key) {
return this.values.has(key);
}
/**
* Delete a key in the store
* @param key
*/
delete(key) {
const hasKey = this.values.has(key);
if (hasKey) {
this.values.delete(key);
}
}
/**
* Delete all entry with prefix keys
* @param keys
*/
deleteKeys(keys) {
keys.forEach((k) => {
const hasKey = this.values.has(k);
if (hasKey) {
this.values.delete(k);
}
});
}
/**
* Delete all entry with prefix keys
* @param prefix
*/
deleteKeysWithPrefix(prefix) {
this.values.forEach((v, k) => {
if (k.startsWith(prefix)) {
this.values.delete(k);
}
});
}
/**
* Clean the store
*/
clean() {
this.values = new Map();
}
/**
* Print the store in the console
* Only for debug
*/
evaluate() {
console.log(this.values);
}
}
/**
* Define the various types of caching strategies
*/
export var CacheStrategies;
(function (CacheStrategies) {
CacheStrategies["CACHE_FIRST"] = "Cache-first";
CacheStrategies["NETWORK_ONLY"] = "Network-only";
CacheStrategies["STALE_WHILE_REVALIDATE"] = "Stale-While-Revalidate";
})(CacheStrategies || (CacheStrategies = {}));
/**
* Export global cache
*/
const cache = new LruCache();
export default cache;