Key Generation & Utilities
Cachemate exports low-level utility functions used for deterministic key generation, filter hashing, and logging.
import {
hashFilters,
getDeterministicString,
buildJoinKey,
buildFlatKey,
buildVersionString,
makeLogger,
type Logger,
} from 'cachemate';
getDeterministicString()
Converts any arbitrary JavaScript data structure (objects, nested arrays, primitives, Dates) into a stable, deterministic string representation by sorting object keys alphabetically at all levels.
import { getDeterministicString } from 'cachemate';
const s1 = getDeterministicString({ b: 2, a: 1 });
const s2 = getDeterministicString({ a: 1, b: 2 });
console.log(s1 === s2); // true: "{a:1,b:2}"
hashFilters()
Computes a deterministic 12-character SHA-1 hex hash for any filter object.
import { hashFilters } from 'cachemate';
const hash = hashFilters({ status: 'ACTIVE', role: 'admin', page: 1 });
console.log(hash); // e.g. "7a9f0c2e3d1b"
buildJoinKey()
Generates a fully qualified composite cache key for multi-table queries.
import { buildJoinKey, type TableRegistry } from 'cachemate';
const registry: TableRegistry = {
entries: {
users: { tag: 'u', versionKey: 'cm:ver:users' },
orders: { tag: 'o', versionKey: 'cm:ver:orders' },
},
};
const key = await buildJoinKey({
registry,
tables: ['orders', 'users'],
filters: { userId: '123' },
versionsProvider: async (keys) => ['5', '2'], // Mock version counters
keyPrefix: 'cm',
});
console.log(key); // "cm:o-u:5:2:a1b2c3d4e5f6"
buildFlatKey()
Generates a flat namespace key with a deterministic filter hash.
import { buildFlatKey } from 'cachemate';
const key = buildFlatKey({
ns: 'rates',
filters: { base: 'USD', target: 'EUR' },
keyPrefix: 'cm',
});
console.log(key); // "cm:rates:d4e5f6a1b2c3"
makeLogger()
Creates a safe, non-throwing logger function that prefixes log statements with the application name and [cachemate].
import { makeLogger } from 'cachemate';
const logger = makeLogger('my-api', (msg) => {
// Forward to Datadog / Winston / Pino
});
logger('Pool failover initiated to node 2');
// Emits: "[my-api][cachemate] Pool failover initiated to node 2"