mic-bot/repo/setup_db.ts
2024-10-23 18:09:10 +02:00

39 lines
1.1 KiB
TypeScript

import {
Kysely,
Migrator,
PostgresDialect,
FileMigrationProvider
} from 'https://cdn.jsdelivr.net/npm/kysely/dist/esm/index.js'
/// <reference types="npm:@types/pg" />
// @deno-types="npm:@types/pg"
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 }
}