import path from "path" ; import "reflect-metadata" ; import { Connection , createConnection } from "typeorm" ; import * as Models from "../entities" ; import { Migration } from "../entities/Migration" ; import { yellow , green , red } from "picocolors" ; var promise ; var dbConnection ; let dbConnectionString = process . env . DATABASE || path . join ( process . cwd ( ) , "database.db" ) ; export function initDatabase ( ) { if ( promise ) return promise ; const type = dbConnectionString . includes ( "://" ) ? dbConnectionString . split ( ":" ) [ 0 ] ?. replace ( "+srv" , "" ) : "sqlite" ; const isSqlite = type . includes ( "sqlite" ) ; console . log ( `[Database] ${ yellow ( `connecting to ${ type } db` ) }` ) ; if ( isSqlite ) { console . log ( `[Database] ${ red ( `You are running sqlite! Please keep in mind that we recommend setting up a dedicated database!` ) }` ) ; } promise = createConnection ( { type , url : isSqlite ? undefined : dbConnectionString , database : isSqlite ? dbConnectionString : undefined , entities : Object . values ( Models ) . filter ( ( x ) => x . constructor . name !== "Object" && x . name ) , synchronize : type !== "mongodb" , logging : false , cache : { duration : 1000 * 3 , } , bigNumberStrings : false , supportBigNumbers : true , name : "default" , migrations : [ path . join ( __dirname , ".." , "migrations" , "*.js" ) ] , } ) ; promise . then ( async ( connection ) => { dbConnection = connection ; if ( connection . migrations . length ) { if ( ! ( await Migration . findOne ( { } ) ) ) { let i = 0 ; await Migration . insert ( connection . migrations . map ( ( x ) => ( { id : i ++ , name : x . name , timestamp : Date . now ( ) , } ) ) ) ; } } await connection . runMigrations ( ) ; console . log ( `[Database] ${ green ( "connected" ) }` ) ; } ) ; return promise ; } export { dbConnection } ; export function closeDatabase ( ) { dbConnection ?. close ( ) ; }