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