Created
June 4, 2024 06:32
-
-
Save gczh/53bae4a128748e8271914289156e4df6 to your computer and use it in GitHub Desktop.
Creates multiple drizzle clients without creating new connections each time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
drizzle as drizzleClient, | |
PostgresJsDatabase, | |
} from "drizzle-orm/postgres-js"; | |
import postgres from "postgres"; | |
import * as database1Schema from "./schemas/database1/schema"; | |
import * as database2Schema from "./schemas/database2/schema"; | |
const createDrizzleClientSingleton = <TSchema extends Record<string, unknown>>( | |
db: string, | |
schema: TSchema | |
): PostgresJsDatabase<TSchema> => { | |
let connectionString = null; | |
if (db === "app1") { | |
connectionString = process.env.APP_1_DATABASE_URL!; | |
} else { | |
connectionString = process.env.APP_2_DATABASE_URL!; | |
} | |
const client = postgres(connectionString); | |
return drizzleClient(client, { schema }); | |
}; | |
// The types here ensure you get correct type completions | |
declare const globalThis: { | |
app1DrizzleGlobal: PostgresJsDatabase<typeof database1Schema>; | |
app2DrizzleGlobal: PostgresJsDatabase<typeof database2Schema>; | |
} & typeof global; | |
const app1Drizzle = | |
globalThis.app1DrizzleGlobal ?? | |
createDrizzleClientSingleton("app1", app1Schema); | |
const app2Drizzle = | |
globalThis.app2DrizzleGlobal ?? | |
createDrizzleClientSingleton("app2", app2Schema); | |
export { crawlerDrizzle, appDrizzle }; | |
if (process.env.NODE_ENV !== "production") { | |
globalThis.app1DrizzleGlobal = app1Drizzle; | |
globalThis.app2DrizzleGlobal = app2Drizzle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment