aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/initializers/database.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/initializers/database.ts')
-rw-r--r--server/initializers/database.ts72
1 files changed, 72 insertions, 0 deletions
diff --git a/server/initializers/database.ts b/server/initializers/database.ts
new file mode 100644
index 000000000..753a06669
--- /dev/null
+++ b/server/initializers/database.ts
@@ -0,0 +1,72 @@
1import fs = require('fs')
2import { join } from 'path'
3import Sequelize = require('sequelize')
4
5import { CONFIG } from './constants'
6// Do not use barrel, we need to load database first
7import { logger } from '../helpers/logger'
8import { isTestInstance } from '../helpers/utils'
9
10const dbname = CONFIG.DATABASE.DBNAME
11const username = CONFIG.DATABASE.USERNAME
12const password = CONFIG.DATABASE.PASSWORD
13
14const database: any = {}
15
16const sequelize = new Sequelize(dbname, username, password, {
17 dialect: 'postgres',
18 host: CONFIG.DATABASE.HOSTNAME,
19 port: CONFIG.DATABASE.PORT,
20 benchmark: isTestInstance(),
21
22 logging: function (message, benchmark) {
23 let newMessage = message
24 if (benchmark !== undefined) {
25 newMessage += ' | ' + benchmark + 'ms'
26 }
27
28 logger.debug(newMessage)
29 }
30})
31
32database.sequelize = sequelize
33
34database.init = function (silent, callback) {
35 if (!callback) {
36 callback = silent
37 silent = false
38 }
39
40 if (!callback) callback = function () { /* empty */ }
41
42 const modelDirectory = join(__dirname, '..', 'models')
43 fs.readdir(modelDirectory, function (err, files) {
44 if (err) throw err
45
46 files.filter(function (file) {
47 // For all models but not utils.js
48 if (file === 'utils.js') return false
49
50 return true
51 })
52 .forEach(function (file) {
53 const model = sequelize.import(join(modelDirectory, file))
54
55 database[model['name']] = model
56 })
57
58 Object.keys(database).forEach(function (modelName) {
59 if ('associate' in database[modelName]) {
60 database[modelName].associate(database)
61 }
62 })
63
64 if (!silent) logger.info('Database %s is ready.', dbname)
65
66 return callback(null)
67 })
68}
69
70// ---------------------------------------------------------------------------
71
72module.exports = database