keycloak-demo/utils/cache.js

52 lines
802 B
JavaScript

class Cache {
constructor () {
this.kv = {}
}
/**
* @param {string} key
* @param {string} value
* @param {boolean?} noOverride
*/
set (key, value, noOverride) {
if (noOverride && key in this.kv) {
throw new Error('key exists')
}
this.kv[key] = value
}
/**
* @param {string} key
* @return {string?}
*/
get (key) {
return this.kv[key] || null
}
/**
* @param {string[]} keys
*/
del (...keys) {
for (const key of keys) {
delete this.kv[key]
}
}
}
let cache = null
exports.new = function () {
if (cache) throw new Error('cache already initiate')
cache = new Cache()
return cache
}
/**
* @return {Cache}
*/
exports.get = function () {
if (!cache) throw new Error('cache not initiate')
return cache
}