@croct/cache
Version:
An abstraction layer for caching.
90 lines (89 loc) • 2.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdaptedCache = void 0;
const node_object_hash_1 = require("node-object-hash");
const HASHER = (0, node_object_hash_1.hasher)({
// Support classes and instances like `ResourceId`
coerce: true,
// Do not differentiate Objects, Sets and Maps constructed in different order
// `new Set([1,2,3])` should match `new Set([3,2,1])`
sort: {
array: false,
typedArray: false,
object: true,
set: true,
map: true,
bigint: true,
},
// Do not trim values, "foo " and "foo" should not match as the same key
trim: false,
});
function identity(value) {
return value;
}
/**
* A cache provider to transform keys and values between composition layers.
*/
class AdaptedCache {
constructor(config) {
this.cache = config.cache;
this.keyTransformer = config.keyTransformer;
this.valueInputTransformer = config.valueInputTransformer;
this.valueOutputTransformer = config.valueOutputTransformer;
}
static transformKeys(cache, keyTransformer) {
return new AdaptedCache({
cache: cache,
keyTransformer: keyTransformer,
valueInputTransformer: identity,
valueOutputTransformer: identity,
});
}
static transformValues(cache, inputTransformer, outputTransformer) {
return new AdaptedCache({
cache: cache,
keyTransformer: identity,
valueInputTransformer: inputTransformer,
valueOutputTransformer: outputTransformer,
});
}
async get(key, loader) {
return this.cache
.get(await this.keyTransformer(key), () => loader(key).then(this.valueInputTransformer))
.then(this.valueOutputTransformer);
}
async set(key, value) {
return this.cache.set(await this.keyTransformer(key), await this.valueInputTransformer(value));
}
async delete(key) {
return this.cache.delete(await this.keyTransformer(key));
}
static createHashSerializer(algorithm) {
if (algorithm === 'passthrough') {
// Do not hash when algorithm is set to `passthrough`
return HASHER.sort.bind(HASHER);
}
const options = {
enc: 'base64',
alg: algorithm,
};
return (value) => HASHER.hash(value, options);
}
/**
* Serializes a JSON compatible value to a string using JSON.stringify.
*
* This is a helper function for type safety.
*/
static jsonSerializer() {
return JSON.stringify;
}
/**
* Deserializes a string into a JSON value using JSON.parse.
*
* This is a helper function for type safety.
*/
static jsonDeserializer() {
return JSON.parse;
}
}
exports.AdaptedCache = AdaptedCache;