diff --git a/src/server/prisma.ts b/src/server/prisma/index.ts similarity index 100% rename from src/server/prisma.ts rename to src/server/prisma/index.ts diff --git a/src/server/prisma/pglite.ts b/src/server/prisma/pglite.ts new file mode 100644 index 00000000..46746574 --- /dev/null +++ b/src/server/prisma/pglite.ts @@ -0,0 +1,25 @@ +import { PGlite } from '@electric-sql/pglite' +import { PrismaPGlite } from 'pglite-prisma-adapter' +import { PrismaClient } from '@prisma/client' +import { readdirSync, readFileSync, statSync } from 'node:fs' + +export const makePgliteClient = () => { + const client = new PGlite() + const adapter = new PrismaPGlite(client) + return { + client, + prisma: new PrismaClient({ adapter }), + } +} + +export const applyMigrations = async (client: PGlite) => { + const prismaMigrationDir = './prisma/migrations' + const directory = readdirSync(prismaMigrationDir).sort() + for (const file of directory) { + const name = `${prismaMigrationDir}/${file}` + if (statSync(name).isDirectory()) { + const migration = readFileSync(`${name}/migration.sql`, 'utf8') + await client.exec(migration) + } + } +} diff --git a/vitest.setup.ts b/vitest.setup.ts index c2853626..1b153b11 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -1,18 +1,13 @@ import { vi } from 'vitest' -import { PGlite } from '@electric-sql/pglite' -import { PrismaPGlite } from 'pglite-prisma-adapter' -import { PrismaClient } from '@prisma/client' -import { readdirSync, readFileSync, statSync } from 'node:fs' +import { makePgliteClient, applyMigrations } from '~/server/prisma/pglite' -const client = new PGlite() -const adapter = new PrismaPGlite(client) -const prisma = new PrismaClient({ adapter }) +const { client, prisma } = makePgliteClient() vi.mock('./src/server/prisma', () => ({ prisma, })) -export const resetDb = async () => { +const resetDb = async () => { try { await client.exec(`DROP SCHEMA public CASCADE`) await client.exec(`CREATE SCHEMA public`) @@ -21,21 +16,9 @@ export const resetDb = async () => { } } -const applyMigrations = async () => { - const prismaMigrationDir = './prisma/migrations' - const directory = readdirSync(prismaMigrationDir).sort() - for (const file of directory) { - const name = `${prismaMigrationDir}/${file}` - if (statSync(name).isDirectory()) { - const migration = readFileSync(`${name}/migration.sql`, 'utf8') - await client.exec(migration) - } - } -} - // Apply migrations before each test beforeEach(async () => { - await applyMigrations() + await applyMigrations(client) }) // Clean up the database after each test