PeerTube/server/initializers/database.js

78 lines
1.9 KiB
JavaScript
Raw Normal View History

'use strict'
2015-06-09 10:41:40 -05:00
2016-12-11 14:50:51 -06:00
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
2015-06-09 10:41:40 -05:00
2016-08-19 14:34:51 -05:00
const constants = require('../initializers/constants')
2016-03-16 16:29:27 -05:00
const logger = require('../helpers/logger')
2016-12-24 09:59:17 -06:00
const utils = require('../helpers/utils')
2015-06-09 10:41:40 -05:00
2016-12-11 14:50:51 -06:00
const database = {}
2016-12-25 02:44:57 -06: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 14:50:51 -06:00
dialect: 'postgres',
host: constants.CONFIG.DATABASE.HOSTNAME,
2016-12-24 09:59:17 -06: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 14:50:51 -06:00
})
2016-12-25 02:44:57 -06:00
database.sequelize = sequelize
database.Sequelize = Sequelize
database.init = init
2016-12-11 14:50:51 -06:00
2016-12-25 02:44:57 -06:00
// ---------------------------------------------------------------------------
2016-12-11 14:50:51 -06:00
2016-12-25 02:44:57 -06:00
module.exports = database
2016-01-31 04:23:52 -06:00
2016-12-25 02:44:57 -06:00
// ---------------------------------------------------------------------------
2016-12-11 14:50:51 -06:00
2016-12-25 02:44:57 -06:00
function init (silent, callback) {
if (!callback) {
callback = silent
silent = false
}
2016-12-11 14:50:51 -06:00
2016-12-25 02:44:57 -06:00
if (!callback) callback = function () {}
2016-12-11 14:50:51 -06:00
2016-12-25 02:44:57 -06:00
const modelDirectory = path.join(__dirname, '..', 'models')
fs.readdir(modelDirectory, function (err, files) {
if (err) throw err
2016-01-31 04:23:52 -06:00
2016-12-25 02:44:57 -06:00
files.filter(function (file) {
// For all models but not utils.js
if (file === 'utils.js') return false
2015-06-09 10:41:40 -05:00
2016-12-25 02:44:57 -06: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 is ready.')
return callback(null)
})
}