summaryrefslogtreecommitdiff
path: root/lib/models/index.js
blob: 0679a7fcc663a0251fdb905aa725e34afd44af8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict'
// external modules
var fs = require('fs')
var path = require('path')
var Sequelize = require('sequelize')
const {cloneDeep} = require('lodash')

// core
var config = require('../config')
var logger = require('../logger')

var dbconfig = cloneDeep(config.db)
dbconfig.logger = config.debug ? logger.info : false

var sequelize = null

// Heroku specific
if (config.dburl) {
  sequelize = new Sequelize(config.dburl, dbconfig)
} else {
  sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, dbconfig)
}

// [Postgres] Handling NULL bytes
// https://github.com/sequelize/sequelize/issues/6485
function stripNullByte (value) {
  value = '' + value
  return value ? value.replace(/\u0000/g, '') : value
}
sequelize.stripNullByte = stripNullByte

function processData (data, _default, process) {
  if (data === undefined) return data
  else return data === null ? _default : (process ? process(data) : data)
}
sequelize.processData = processData

var db = {}

fs.readdirSync(__dirname)
    .filter(function (file) {
      return (file.indexOf('.') !== 0) && (file !== 'index.js')
    })
    .forEach(function (file) {
      var model = sequelize.import(path.join(__dirname, file))
      db[model.name] = model
    })

Object.keys(db).forEach(function (modelName) {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db)
  }
})

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db