UNPKG

@zenweb/cache

Version:
23 lines (22 loc) 732 B
/** * 缓存中间件 * - 缓存 ctx.success() 结果 * - fail() 时不缓存 * @param key 不指定 `key` 则默认使用 `ctx.path`,`key: null` 不适用使用缓存 */ export function cached(key, opt) { return async function cachedMiddleware(ctx, next) { const _key = typeof key === 'string' ? key : typeof key === 'function' ? await key(ctx) : typeof key === 'undefined' ? `CACHED-PATH:${ctx.path}` : null; if (!_key) { return next(); } const result = await ctx.core.cache2.lockGet(_key, async function () { await next(); return ctx.successData; }, opt); ctx.success(result); }; }