From e36cfbca835d01eaf7491f49555579ebc330cb42 Mon Sep 17 00:00:00 2001 From: luorijun Date: Mon, 29 Sep 2025 12:06:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E8=A7=A3=E5=86=B3=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E6=97=B6=E5=88=9D=E5=A7=8B=E5=8C=96=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib/drizzle/index.ts | 20 ++++++++++---------- src/lib/redis.ts | 15 ++++++++------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/lib/drizzle/index.ts b/src/lib/drizzle/index.ts index 39ac75b..2daa81e 100644 --- a/src/lib/drizzle/index.ts +++ b/src/lib/drizzle/index.ts @@ -1,20 +1,20 @@ -import 'dotenv/config' -import { drizzle as client, MySql2Database } from 'drizzle-orm/mysql2' +import 'server-only' +import { drizzle as client, type MySql2Database } from 'drizzle-orm/mysql2' import * as schema from './schema' -declare global { - var drizzle: MySql2Database | undefined -} +const globalForDrizzle = globalThis as { drizzle?: MySql2Database } -const drizzle = new Proxy({} as MySql2Database, { +const proxy = new Proxy({} as MySql2Database, { get(_, prop) { - if (!global.drizzle && process.env.NODE_ENV !== 'production') { - global.drizzle = client(process.env.DATABASE_URL!, { mode: 'default', schema }) + if (!globalForDrizzle.drizzle) { + globalForDrizzle.drizzle = client(process.env.DATABASE_URL!, { mode: 'default', schema }) } - return global.drizzle![prop as keyof typeof global.drizzle] + + const drizzle = globalForDrizzle.drizzle + return drizzle[prop as keyof typeof drizzle] }, }) -export default drizzle +export default proxy export * from './schema' export * from 'drizzle-orm' diff --git a/src/lib/redis.ts b/src/lib/redis.ts index b77f64f..02a1c18 100644 --- a/src/lib/redis.ts +++ b/src/lib/redis.ts @@ -1,14 +1,15 @@ import 'server-only' -import { createClient } from 'redis' +import { createClient, type RedisClientType } from 'redis' -declare global { - var redis: ReturnType | undefined +const globalForRedis = globalThis as { redis?: RedisClientType } + +if (!globalForRedis.redis) { + globalForRedis.redis = createClient({ url: process.env.REDIS_URL }) } -const client = global.redis || createClient({ url: process.env.REDIS_URL }) -if (process.env.NODE_ENV !== 'production') { - global.redis = client +const redis = globalForRedis.redis +if (process.env.NODE_ENV === 'production') { + await redis.connect() } -const redis = await client.connect() export default redis