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 +}