ionian/src/database.ts

36 lines
1022 B
TypeScript
Raw Normal View History

2020-12-31 03:06:16 +09:00
import { existsSync } from 'fs';
import Knex from 'knex';
2021-01-09 20:27:58 +09:00
import {Knex as KnexConfig} from './config';
2021-01-15 18:43:36 +09:00
import { get_setting } from './SettingConfig';
2020-12-31 03:06:16 +09:00
export async function connectDB(){
2021-01-09 20:27:58 +09:00
const config = KnexConfig.config;
2021-01-10 03:04:30 +09:00
const env = get_setting().mode;
2021-01-09 23:23:37 +09:00
const init_need = !existsSync(config[env].connection.filename);
2020-12-31 03:06:16 +09:00
const knex = Knex(config[env]);
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;
}
2021-01-09 20:27:58 +09:00
if(init_need){
2021-01-09 23:23:37 +09:00
console.log("first execute: initialize database...");
2021-01-09 20:27:58 +09:00
const migrate = await import("../migrations/initial");
await migrate.up(knex);
}
2020-12-31 03:06:16 +09:00
return knex;
}