yap-blog/tests/e2e/setup-db.ts
2026-07-02 21:32:33 -04:00

40 lines
1.4 KiB
TypeScript

import "dotenv/config";
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { Pool } from "pg";
import { seed } from "../../scripts/seed";
/**
* Resets the dedicated E2E database and seeds it. Runs as a standalone
* step BEFORE `playwright test` (see the test:e2e script) because
* Playwright boots the web server before globalSetup would run.
*/
async function main() {
const url =
process.env.E2E_DATABASE_URL || "postgresql://blog:blog@localhost:5434/blog_e2e";
const pool = new Pool({ connectionString: url, max: 1 });
try {
await pool.query("select 1");
} catch (error) {
await pool.end();
throw new Error(
`Could not reach the E2E database at ${url}.\n` +
`Start it with: docker compose up -d\n(${String(error)})`,
);
}
// The drizzle schema holds the migration journal — drop it too, or the
// migrator will consider everything applied against the empty schema.
await pool.query(
"DROP SCHEMA public CASCADE; CREATE SCHEMA public; DROP SCHEMA IF EXISTS drizzle CASCADE;",
);
await migrate(drizzle(pool), { migrationsFolder: "./drizzle" });
await pool.end();
await seed(url, (msg) => console.log(`[e2e-setup] ${msg}`));
console.log("[e2e-setup] database ready");
}
main().catch((error) => {
console.error("[e2e-setup] failed:", error);
process.exit(1);
});