2017-03-14 05:02:43 +00:00
|
|
|
'use strict'
|
2016-04-20 10:03:55 +00:00
|
|
|
// external modules
|
2017-03-08 10:45:51 +00:00
|
|
|
var fs = require('fs')
|
|
|
|
var path = require('path')
|
|
|
|
var Sequelize = require('sequelize')
|
2017-04-12 17:57:55 +00:00
|
|
|
const {cloneDeep} = require('lodash')
|
2016-04-20 10:03:55 +00:00
|
|
|
|
|
|
|
// core
|
2017-04-12 16:20:28 +00:00
|
|
|
var config = require('../config')
|
|
|
|
var logger = require('../logger')
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2017-04-12 17:57:55 +00:00
|
|
|
var dbconfig = cloneDeep(config.db)
|
2017-06-04 19:52:25 +00:00
|
|
|
dbconfig.logging = config.debug ? logger.info : false
|
2016-12-12 02:18:12 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
var sequelize = null
|
2016-12-22 05:23:17 +00:00
|
|
|
|
2016-12-22 11:42:00 +00:00
|
|
|
// Heroku specific
|
2018-03-07 14:17:35 +00:00
|
|
|
if (config.dbURL) {
|
|
|
|
sequelize = new Sequelize(config.dbURL, dbconfig)
|
2017-03-08 10:45:51 +00:00
|
|
|
} else {
|
|
|
|
sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, dbconfig)
|
|
|
|
}
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2017-01-02 03:05:05 +00:00
|
|
|
// [Postgres] Handling NULL bytes
|
|
|
|
// https://github.com/sequelize/sequelize/issues/6485
|
2017-03-08 10:45:51 +00:00
|
|
|
function stripNullByte (value) {
|
2017-03-15 14:12:24 +00:00
|
|
|
value = '' + value
|
2017-03-08 10:45:51 +00:00
|
|
|
return value ? value.replace(/\u0000/g, '') : value
|
2017-01-02 03:05:05 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
sequelize.stripNullByte = stripNullByte
|
2017-01-02 03:05:05 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
function processData (data, _default, process) {
|
|
|
|
if (data === undefined) return data
|
|
|
|
else return data === null ? _default : (process ? process(data) : data)
|
2017-01-02 03:05:36 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
sequelize.processData = processData
|
2017-01-02 03:05:36 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
var db = {}
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
fs.readdirSync(__dirname)
|
2016-04-20 10:03:55 +00:00
|
|
|
.filter(function (file) {
|
2017-03-08 10:45:51 +00:00
|
|
|
return (file.indexOf('.') !== 0) && (file !== 'index.js')
|
2016-04-20 10:03:55 +00:00
|
|
|
})
|
|
|
|
.forEach(function (file) {
|
2017-03-08 10:45:51 +00:00
|
|
|
var model = sequelize.import(path.join(__dirname, file))
|
|
|
|
db[model.name] = model
|
|
|
|
})
|
2016-04-20 10:03:55 +00:00
|
|
|
|
|
|
|
Object.keys(db).forEach(function (modelName) {
|
2017-03-08 10:45:51 +00:00
|
|
|
if ('associate' in db[modelName]) {
|
|
|
|
db[modelName].associate(db)
|
|
|
|
}
|
|
|
|
})
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
db.sequelize = sequelize
|
|
|
|
db.Sequelize = Sequelize
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
module.exports = db
|