mic-bot/repo/setup_db.ts

32 lines
1.0 KiB
TypeScript
Raw Normal View History

2024-10-19 10:00:35 +00:00
import { Kysely, Migrator, PostgresDialect } from 'npm:kysely'
import { FileMigrationProvider } from "npm:kysely";
import { Pool } from "npm:pg";
import { Database } from "./scheme.ts"
import { CompiledConfig } from "../cfg/config.ts";
import { promises as fs } from 'node:fs'
import * as path from 'node:path'
export type SetupDbOutput = {
pool: Pool,
db: Kysely<Database>,
}
export const setupDB = async (cfg: CompiledConfig): Promise<SetupDbOutput> => {
const pool = new Pool(cfg.pgPoolCfg)
const dialect = new PostgresDialect({ pool })
const db = new Kysely<Database>({ dialect })
if (cfg.migrationCfg && cfg.migrationCfg.applyMigrations) {
const migrator = new Migrator({
db,
provider: new FileMigrationProvider({
fs,
path,
migrationFolder: cfg.migrationCfg.migrationsPath,
}),
allowUnorderedMigrations: true
})
await migrator.migrateToLatest()
}
return { pool, db }
}