import { existsSync } from 'fs'; import Knex from 'knex'; import {Knex as KnexConfig} from './config'; import { get_setting } from './SettingConfig'; export async function connectDB(){ const config = KnexConfig.config; const env = get_setting().mode; const init_need = !existsSync(config[env].connection.filename); 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; } if(init_need){ console.log("first execute: initialize database..."); const migrate = await import("../migrations/initial"); await migrate.up(knex); } return knex; }