diff --git a/db/client.ts b/db/client.ts new file mode 100644 index 0000000..0957a20 --- /dev/null +++ b/db/client.ts @@ -0,0 +1,37 @@ +import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; +import postgres from "postgres"; + +import * as schema from "@/db/schema"; + +type Database = PostgresJsDatabase; + +let database: Database | undefined; +let client: ReturnType | undefined; + +export function getDb(): Database { + const databaseUrl = process.env.DATABASE_URL; + + if (!databaseUrl) { + throw new Error( + "DATABASE_URL is required for database-backed routes. Copy .env.example to .env and configure it.", + ); + } + + if (!database) { + client = postgres(databaseUrl, { + max: Number(process.env.DATABASE_POOL_SIZE ?? 10), + prepare: false, + }); + database = drizzle(client, { schema }); + } + + return database; +} + +export async function closeDb(): Promise { + await client?.end(); + client = undefined; + database = undefined; +} + +export type { Database }; diff --git a/db/index.ts b/db/index.ts index 6967a41..9a9054b 100644 --- a/db/index.ts +++ b/db/index.ts @@ -1,39 +1,3 @@ import "server-only"; -import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; -import postgres from "postgres"; - -import * as schema from "@/db/schema"; - -type Database = PostgresJsDatabase; - -let database: Database | undefined; -let client: ReturnType | undefined; - -export function getDb(): Database { - const databaseUrl = process.env.DATABASE_URL; - - if (!databaseUrl) { - throw new Error( - "DATABASE_URL is required for database-backed routes. Copy .env.example to .env and configure it.", - ); - } - - if (!database) { - client = postgres(databaseUrl, { - max: Number(process.env.DATABASE_POOL_SIZE ?? 10), - prepare: false, - }); - database = drizzle(client, { schema }); - } - - return database; -} - -export async function closeDb(): Promise { - await client?.end(); - client = undefined; - database = undefined; -} - -export type { Database }; +export { closeDb, getDb, type Database } from "@/db/client"; diff --git a/scripts/migrate.ts b/scripts/migrate.ts index 4741133..c0f8a1a 100644 --- a/scripts/migrate.ts +++ b/scripts/migrate.ts @@ -1,6 +1,6 @@ import { migrate } from "drizzle-orm/postgres-js/migrator"; -import { closeDb, getDb } from "@/db"; +import { closeDb, getDb } from "@/db/client"; await migrate(getDb(), { migrationsFolder: "drizzle" }); await closeDb(); diff --git a/scripts/seed-templates.ts b/scripts/seed-templates.ts index 464514c..ee8ef63 100644 --- a/scripts/seed-templates.ts +++ b/scripts/seed-templates.ts @@ -1,4 +1,4 @@ -import { closeDb, getDb } from "@/db"; +import { closeDb, getDb } from "@/db/client"; import { templates } from "@/db/schema"; import { builtInTemplates } from "@/lib/templates";