UNPKG

@zenweb/cache

Version:
58 lines (57 loc) 1.53 kB
import { cacheKey } from "./utils.js"; export class CacheNotExists extends Error { } export class CacheHelper { _cache; _key; _fetch; _opt; constructor(_cache, _key, _fetch, _opt) { this._cache = _cache; this._key = _key; this._fetch = _fetch; this._opt = _opt; } /** * 取得缓存 key */ key(...param) { if (typeof this._key === 'function') { return this._key(...param); } else { return cacheKey(this._key, ...param); } } /** * 取得缓存 * * 如果已定义 `fetch` 参数当缓存不存在时使用 `fetch` 获取并设置缓存,否则抛出异常 */ async get(...param) { const _key = await this.key(...param); const _fetch = this._fetch; if (_fetch) { return this._cache.lockGet(_key, () => _fetch(...param), { parse: true, noWait: false, ...this._opt }); } const data = await this._cache.get(_key, { parse: true, ...this._opt }); if (data === undefined) { throw new CacheNotExists(`cache not exists: ${_key}`); } return data; } /** * 设置缓存 */ async set(value, ...param) { const _key = await this.key(...param); return this._cache.set(_key, value, this._opt); } /** * 删除缓存 */ async del(...param) { const _key = await this.key(...param); return this._cache.del(_key); } }