ionian/packages/server/src/database.ts

48 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-03-26 23:58:26 +09:00
import { existsSync } from "fs";
import Knex from "knex";
import { Knex as KnexConfig } from "./config";
import { get_setting } from "./SettingConfig";
export async function connectDB() {
const env = get_setting().mode;
const config = KnexConfig.config[env];
if (!config.connection) {
throw new Error("connection options required.");
}
const connection = config.connection;
if (typeof connection === "string") {
throw new Error("unknown connection options");
}
if (typeof connection === "function") {
throw new Error("connection provider not supported...");
}
if (!("filename" in connection)) {
throw new Error("sqlite3 config need");
}
const init_need = !existsSync(connection.filename);
const knex = Knex(config);
let tries = 0;
for (;;) {
try {
console.log("try to connect db");
await knex.raw("select 1 + 1;");
console.log("connect success");
} catch (err) {
if (tries < 3) {
tries++;
console.error(`connection fail ${err} retry...`);
continue;
} else {
throw err;
}
}
break;
}
if (init_need) {
console.log("first execute: initialize database...");
const migrate = await import("../migrations/initial");
await migrate.up(knex);
}
return knex;
}