feat(cache): 新增 store-factory(CACHE_DRIVER 切换)

This commit is contained in:
SpecialX
2026-07-05 17:52:24 +08:00
parent 1756ac21a8
commit 13409e55f1

36
src/shared/lib/cache/store-factory.ts vendored Normal file
View File

@@ -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<CacheStore> | null = null
/**
* 获取当前进程的 CacheStore 实例。
*
* - 默认返回 MemoryCacheStore
* - 当 CACHE_DRIVER=redis 时动态加载 RedisCacheStore
* - Redis 实现懒加载 @upstash/redis 依赖,未安装时首次调用抛错
*
* 返回 PromiseRedis 实现需动态 import 模块,故为异步。
*/
export async function getCacheStore(): Promise<CacheStore> {
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
}