@cache-kit/cache-key
v0.1.1
Published
Deterministic, URL-style cache key generation from any JS object — sorted properties, optional array normalization, value exclusion, and a best-effort reverse parse. Standalone; no dependency on @cache-kit/cache.
Downloads
282
Readme
@cache-kit/cache-key
Deterministic, URL-style cache key generation from any JS object. Fully
standalone — no dependency on @cache-kit/cache or anything else. Also
available as cache.buildKey(...) if you're using @cache-kit/cache.
npm install @cache-kit/cache-keyimport { buildKey, parseKey } from '@cache-kit/cache-key';
buildKey({ category: 1, price: { min: 100 } });
// => "category=1&price[min]=100"
buildKey({ price: { min: 100 }, category: 1 });
// => "category=1&price[min]=100" (same key — property order never matters)Options
buildKey(input, {
excludedValues: [undefined, null, ''], // default: [undefined]
normalizeArrays: true, // default: false (order preserved)
hash: 'sha256', // default: false (readable string)
hashLength: 16, // truncate the digest; default: full length
});parseKey — read this before relying on it
parseKey reverses the structure of a key perfectly (bracket notation is
naturally invertible). It does not guarantee recovering the exact
original value, for three reasons, all deliberate tradeoffs rather than
bugs:
- Exclusion is destructive by design.
excludedValueserases information from the key entirely — that's the point (so{a: 1, b: undefined}and{a: 1}hit the same cache entry). There's no way to tell from the key alone thatbwas ever present. - No type tags.
100(number) and"100"(string) serialize identically, soparseKeyalways resolves ambiguous scalars the same way (numeric/boolean-looking strings become numbers/booleans). This is the same well-known limitation the popularqslibrary'sparse()has. normalizeArraysis also destructive to original ordering, for the same reason as (1).
Safe use: debugging, logging, or an admin UI showing "what filters produced this cache entry." Not safe: reconstructing a query object you then feed into a typed query builder or DB call expecting exact types — keep storing the original object for that.
Hashed output (hash option set) cannot be parsed — hashing is one-way.
License
MIT
