@delicious-simplicity/typekey
Version:
TypeScript library for generating cache keys with type safety
50 lines (49 loc) • 1.68 kB
JavaScript
var c = Object.defineProperty;
var y = (r, t, e) => t in r ? c(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
var i = (r, t, e) => y(r, typeof t != "symbol" ? t + "" : t, e);
class s extends Error {
constructor(t) {
super(t), this.name = "KeyDictionaryError";
}
}
function h(r) {
return Object.prototype.toString.call(r) === "[object Object]";
}
function u(r) {
if (!h(r)) return !1;
const t = r.constructor;
if (t === void 0) return !0;
const e = t.prototype;
return !(!h(e) || !e.hasOwnProperty("isPrototypeOf") || Object.getPrototypeOf(r) !== Object.prototype);
}
class f {
constructor(t, e = {}) {
i(this, "prefixParamsMap");
i(this, "maxKeyLength");
i(this, "throwOnMaxLengthViolation");
if (this.prefixParamsMap = t, e.throwOnMaxLengthViolation && e.maxKeyLength === void 0)
throw new s("maxKeyLength must be provided when throwOnMaxLengthViolation is true");
this.maxKeyLength = e.maxKeyLength ?? Number.POSITIVE_INFINITY, this.throwOnMaxLengthViolation = e.throwOnMaxLengthViolation ?? !1;
}
hashKeyParts(t) {
return JSON.stringify(
t,
(e, n) => u(n) ? Object.keys(n).sort().reduce((o, a) => (o[a] = n[a], o), {}) : n
);
}
generateKey(t, e) {
const n = this.hashKeyParts(
this.prefixParamsMap[t].sort().map((a) => String(e[a]))
), o = `${String(t)}:${n}`;
if (o.length > this.maxKeyLength) {
if (this.throwOnMaxLengthViolation)
throw new s(`Generated key exceeds maximum length of ${this.maxKeyLength}`);
return o.slice(0, this.maxKeyLength);
}
return o;
}
}
export {
f as KeyDictionary,
s as KeyDictionaryError
};