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';
|
2020-12-31 03:06:16 +09:00
|
|
|
|
|
|
|
export async function connectDB(){
|
|
|
|
const env = process.env.NODE_ENV || 'development';
|
2021-01-09 20:27:58 +09:00
|
|
|
const config = KnexConfig.config;
|
|
|
|
if(env != "production" && env != "development"){
|
|
|
|
throw new Error("process unknown value in NODE_ENV: must be either \"development\" or \"production\"");
|
|
|
|
}
|
|
|
|
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){
|
|
|
|
const migrate = await import("../migrations/initial");
|
|
|
|
await migrate.up(knex);
|
|
|
|
}
|
2020-12-31 03:06:16 +09:00
|
|
|
return knex;
|
|
|
|
}
|