1 import fs = require('fs')
2 import { join } from 'path'
3 import Sequelize = require('sequelize')
5 import { CONFIG } from './constants'
6 // Do not use barrel, we need to load database first
7 import { logger } from '../helpers/logger'
8 import { isTestInstance } from '../helpers/utils'
10 const dbname = CONFIG.DATABASE.DBNAME
11 const username = CONFIG.DATABASE.USERNAME
12 const password = CONFIG.DATABASE.PASSWORD
14 const database: any = {}
16 const sequelize = new Sequelize(dbname, username, password, {
18 host: CONFIG.DATABASE.HOSTNAME,
19 port: CONFIG.DATABASE.PORT,
20 benchmark: isTestInstance(),
22 logging: function (message, benchmark) {
23 let newMessage = message
24 if (benchmark !== undefined) {
25 newMessage += ' | ' + benchmark + 'ms'
28 logger.debug(newMessage)
32 database.sequelize = sequelize
34 database.init = function (silent, callback) {
40 if (!callback) callback = function () { /* empty */ }
42 const modelDirectory = join(__dirname, '..', 'models')
43 fs.readdir(modelDirectory, function (err, files) {
46 files.filter(function (file) {
47 // For all models but not utils.js
48 if (file === 'utils.js') return false
52 .forEach(function (file) {
53 const model = sequelize.import(join(modelDirectory, file))
55 database[model['name']] = model
58 Object.keys(database).forEach(function (modelName) {
59 if ('associate' in database[modelName]) {
60 database[modelName].associate(database)
64 if (!silent) logger.info('Database %s is ready.', dbname)
70 // ---------------------------------------------------------------------------
72 module.exports = database