Fix standard lint
[oweals/peertube.git] / server / initializers / database.js
1 'use strict'
2
3 const fs = require('fs')
4 const path = require('path')
5 const Sequelize = require('sequelize')
6
7 const constants = require('../initializers/constants')
8 const logger = require('../helpers/logger')
9 const utils = require('../helpers/utils')
10
11 const database = {}
12
13 const dbname = constants.CONFIG.DATABASE.DBNAME
14 const username = constants.CONFIG.DATABASE.USERNAME
15 const password = constants.CONFIG.DATABASE.PASSWORD
16
17 const sequelize = new Sequelize(dbname, username, password, {
18   dialect: 'postgres',
19   host: constants.CONFIG.DATABASE.HOSTNAME,
20   port: constants.CONFIG.DATABASE.PORT,
21   benchmark: utils.isTestInstance(),
22
23   logging: function (message, benchmark) {
24     let newMessage = message
25     if (benchmark !== undefined) {
26       newMessage += ' | ' + benchmark + 'ms'
27     }
28
29     logger.debug(newMessage)
30   }
31 })
32
33 database.sequelize = sequelize
34 database.Sequelize = Sequelize
35 database.init = init
36
37 // ---------------------------------------------------------------------------
38
39 module.exports = database
40
41 // ---------------------------------------------------------------------------
42
43 function init (silent, callback) {
44   if (!callback) {
45     callback = silent
46     silent = false
47   }
48
49   if (!callback) callback = function () {}
50
51   const modelDirectory = path.join(__dirname, '..', 'models')
52   fs.readdir(modelDirectory, function (err, files) {
53     if (err) throw err
54
55     files.filter(function (file) {
56       // For all models but not utils.js
57       if (file === 'utils.js') return false
58
59       return true
60     })
61     .forEach(function (file) {
62       const model = sequelize.import(path.join(modelDirectory, file))
63
64       database[model.name] = model
65     })
66
67     Object.keys(database).forEach(function (modelName) {
68       if ('associate' in database[modelName]) {
69         database[modelName].associate(database)
70       }
71     })
72
73     if (!silent) logger.info('Database is ready.')
74
75     return callback(null)
76   })
77 }