]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/initializers/database.js
Update migrations code
[github/Chocobozzz/PeerTube.git] / server / initializers / database.js
CommitLineData
9f10b292 1'use strict'
8c308c2b 2
feb4bdfd
C
3const fs = require('fs')
4const path = require('path')
5const Sequelize = require('sequelize')
8c308c2b 6
e861452f 7const constants = require('../initializers/constants')
f0f5567b 8const logger = require('../helpers/logger')
7920c273 9const utils = require('../helpers/utils')
8c308c2b 10
feb4bdfd
C
11const database = {}
12
b769007f
C
13const dbname = constants.CONFIG.DATABASE.DBNAME
14const username = constants.CONFIG.DATABASE.USERNAME
15const password = constants.CONFIG.DATABASE.PASSWORD
16
17const sequelize = new Sequelize(dbname, username, password, {
feb4bdfd
C
18 dialect: 'postgres',
19 host: constants.CONFIG.DATABASE.HOSTNAME,
7920c273
C
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 }
feb4bdfd
C
31})
32
b769007f
C
33database.sequelize = sequelize
34database.Sequelize = Sequelize
35database.init = init
feb4bdfd 36
b769007f 37// ---------------------------------------------------------------------------
feb4bdfd 38
b769007f 39module.exports = database
c45f7f84 40
b769007f 41// ---------------------------------------------------------------------------
feb4bdfd 42
b769007f
C
43function init (silent, callback) {
44 if (!callback) {
45 callback = silent
46 silent = false
47 }
feb4bdfd 48
b769007f 49 if (!callback) callback = function () {}
feb4bdfd 50
b769007f
C
51 const modelDirectory = path.join(__dirname, '..', 'models')
52 fs.readdir(modelDirectory, function (err, files) {
53 if (err) throw err
c45f7f84 54
b769007f
C
55 files.filter(function (file) {
56 // For all models but not utils.js
57 if (file === 'utils.js') return false
8c308c2b 58
b769007f
C
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}