UNPKG

@naturalcycles/db-lib

Version:

Lowest Common Denominator API to supported Databases

29 lines (28 loc) 906 B
import { localTime } from '@naturalcycles/js-lib/datetime/localTime.js'; import { MISS } from '@naturalcycles/js-lib/types'; /** * AsyncMemoCache implementation, backed by CommonKeyValueDao. * * Does NOT support persisting Errors, skips them instead. * * Also, does not support .clear(), as it's more dangerous than useful to actually * clear the whole table/cache. */ export class CommonKeyValueDaoMemoCache { cfg; constructor(cfg) { this.cfg = cfg; } async get(k) { return (await this.cfg.dao.getById(k)) || MISS; } async set(k, v) { const opt = this.cfg.ttl ? { expireAt: (localTime.nowUnix() + this.cfg.ttl) } : undefined; await this.cfg.dao.save(k, v, opt); } async clear() { throw new Error('CommonKeyValueDaoMemoCache.clear is not supported, because cache is expected to be persistent'); } }