PeerTube/server/initializers/database.js

78 lines
1.9 KiB
JavaScript
Raw Normal View History

'use strict'
2015-06-09 17:41:40 +02:00
2016-12-11 21:50:51 +01:00
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
2015-06-09 17:41:40 +02:00
2016-08-19 21:34:51 +02:00
const constants = require('../initializers/constants')
2016-03-16 22:29:27 +01:00
const logger = require('../helpers/logger')
2016-12-24 16:59:17 +01:00
const utils = require('../helpers/utils')
2015-06-09 17:41:40 +02:00
2016-12-11 21:50:51 +01:00
const database = {}
2016-12-25 09:44:57 +01:00
const dbname = constants.CONFIG.DATABASE.DBNAME
const username = constants.CONFIG.DATABASE.USERNAME
const password = constants.CONFIG.DATABASE.PASSWORD
const sequelize = new Sequelize(dbname, username, password, {
2016-12-11 21:50:51 +01:00
dialect: 'postgres',
host: constants.CONFIG.DATABASE.HOSTNAME,
2016-12-24 16:59:17 +01:00
port: constants.CONFIG.DATABASE.PORT,
benchmark: utils.isTestInstance(),
logging: function (message, benchmark) {
let newMessage = message
if (benchmark !== undefined) {
newMessage += ' | ' + benchmark + 'ms'
}
logger.debug(newMessage)
}
2016-12-11 21:50:51 +01:00
})
2016-12-25 09:44:57 +01:00
database.sequelize = sequelize
database.Sequelize = Sequelize
database.init = init
2016-12-11 21:50:51 +01:00
2016-12-25 09:44:57 +01:00
// ---------------------------------------------------------------------------
2016-12-11 21:50:51 +01:00
2016-12-25 09:44:57 +01:00
module.exports = database
2016-01-31 11:23:52 +01:00
2016-12-25 09:44:57 +01:00
// ---------------------------------------------------------------------------
2016-12-11 21:50:51 +01:00
2016-12-25 09:44:57 +01:00
function init (silent, callback) {
if (!callback) {
callback = silent
silent = false
}
2016-12-11 21:50:51 +01:00
2016-12-25 09:44:57 +01:00
if (!callback) callback = function () {}
2016-12-11 21:50:51 +01:00
2016-12-25 09:44:57 +01:00
const modelDirectory = path.join(__dirname, '..', 'models')
fs.readdir(modelDirectory, function (err, files) {
if (err) throw err
2016-01-31 11:23:52 +01:00
2016-12-25 09:44:57 +01:00
files.filter(function (file) {
// For all models but not utils.js
if (file === 'utils.js') return false
2015-06-09 17:41:40 +02:00
2016-12-25 09:44:57 +01:00
return true
})
.forEach(function (file) {
const model = sequelize.import(path.join(modelDirectory, file))
database[model.name] = model
})
Object.keys(database).forEach(function (modelName) {
if ('associate' in database[modelName]) {
database[modelName].associate(database)
}
})
if (!silent) logger.info('Database %s is ready.', dbname)
2016-12-25 09:44:57 +01:00
return callback(null)
})
}