From 13409e55f1a44e78530db0c2011238bf0d5d9000 Mon Sep 17 00:00:00 2001 From: SpecialX <47072643+wangxiner55@users.noreply.github.com> Date: Sun, 5 Jul 2026 17:52:24 +0800 Subject: [PATCH] =?UTF-8?q?feat(cache):=20=E6=96=B0=E5=A2=9E=20store-facto?= =?UTF-8?q?ry=EF=BC=88CACHE=5FDRIVER=20=E5=88=87=E6=8D=A2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/shared/lib/cache/store-factory.ts | 36 +++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/shared/lib/cache/store-factory.ts diff --git a/src/shared/lib/cache/store-factory.ts b/src/shared/lib/cache/store-factory.ts new file mode 100644 index 0000000..5613495 --- /dev/null +++ b/src/shared/lib/cache/store-factory.ts @@ -0,0 +1,36 @@ +import "server-only" + +import { env } from "@/env.mjs" + +import type { CacheStore } from "./types" +import { MemoryCacheStore } from "./memory-store" + +let singleton: CacheStore | null = null +let loadPromise: Promise | null = null + +/** + * 获取当前进程的 CacheStore 实例。 + * + * - 默认返回 MemoryCacheStore + * - 当 CACHE_DRIVER=redis 时动态加载 RedisCacheStore + * - Redis 实现懒加载 @upstash/redis 依赖,未安装时首次调用抛错 + * + * 返回 Promise:Redis 实现需动态 import 模块,故为异步。 + */ +export async function getCacheStore(): Promise { + if (singleton) return singleton + if (loadPromise) return loadPromise + + loadPromise = (async () => { + if (env.CACHE_DRIVER === "redis") { + const { RedisCacheStore } = await import("./redis-store") + singleton = new RedisCacheStore() + } else { + singleton = new MemoryCacheStore() + } + loadPromise = null + return singleton + })() + + return loadPromise +}