db.js 3.24 KB
Newer Older
1
const _ = require('lodash')
2 3
const fs = require('fs')
const path = require('path')
4
const Promise = require('bluebird')
5
const Sequelize = require('sequelize')
6

7
/* global WIKI */
8 9

const operatorsAliases = {
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
  $eq: Sequelize.Op.eq,
  $ne: Sequelize.Op.ne,
  $gte: Sequelize.Op.gte,
  $gt: Sequelize.Op.gt,
  $lte: Sequelize.Op.lte,
  $lt: Sequelize.Op.lt,
  $not: Sequelize.Op.not,
  $in: Sequelize.Op.in,
  $notIn: Sequelize.Op.notIn,
  $is: Sequelize.Op.is,
  $like: Sequelize.Op.like,
  $notLike: Sequelize.Op.notLike,
  $iLike: Sequelize.Op.iLike,
  $notILike: Sequelize.Op.notILike,
  $regexp: Sequelize.Op.regexp,
  $notRegexp: Sequelize.Op.notRegexp,
  $iRegexp: Sequelize.Op.iRegexp,
  $notIRegexp: Sequelize.Op.notIRegexp,
  $between: Sequelize.Op.between,
  $notBetween: Sequelize.Op.notBetween,
  $overlap: Sequelize.Op.overlap,
  $contains: Sequelize.Op.contains,
  $contained: Sequelize.Op.contained,
  $adjacent: Sequelize.Op.adjacent,
  $strictLeft: Sequelize.Op.strictLeft,
  $strictRight: Sequelize.Op.strictRight,
  $noExtendRight: Sequelize.Op.noExtendRight,
  $noExtendLeft: Sequelize.Op.noExtendLeft,
  $and: Sequelize.Op.and,
  $or: Sequelize.Op.or,
  $any: Sequelize.Op.any,
  $all: Sequelize.Op.all,
  $values: Sequelize.Op.values,
  $col: Sequelize.Op.col
44
}
45 46 47 48 49

/**
 * PostgreSQL DB module
 */
module.exports = {
50 51
  Sequelize,
  Op: Sequelize.Op,
52 53 54 55 56 57 58 59

  /**
   * Initialize DB
   *
   * @return     {Object}  DB instance
   */
  init() {
    let self = this
60
    let dbModelsPath = path.join(WIKI.SERVERPATH, 'models')
61 62 63

    // Define Sequelize instance

64 65 66
    this.inst = new this.Sequelize(WIKI.config.db.db, WIKI.config.db.user, WIKI.config.db.pass, {
      host: WIKI.config.db.host,
      port: WIKI.config.db.port,
67 68 69 70 71
      dialect: 'postgres',
      pool: {
        max: 10,
        min: 0,
        idle: 10000
72
      },
73
      logging: log => { WIKI.logger.log('debug', log) },
74
      operatorsAliases
75 76 77 78
    })

    // Attempt to connect and authenticate to DB

79
    this.inst.authenticate().then(() => {
80
      WIKI.logger.info('Database (PostgreSQL) connection: [ OK ]')
81
    }).catch(err => {
82 83
      WIKI.logger.error('Failed to connect to PostgreSQL instance.')
      WIKI.logger.error(err)
84
      process.exit(1)
85 86 87 88 89 90
    })

    // Load DB Models

    fs
      .readdirSync(dbModelsPath)
NGPixel's avatar
NGPixel committed
91
      .filter(file => {
92 93
        return (file.indexOf('.') !== 0 && file.indexOf('_') !== 0)
      })
NGPixel's avatar
NGPixel committed
94
      .forEach(file => {
95 96 97 98 99 100 101 102
        let modelName = _.upperFirst(_.camelCase(_.split(file, '.')[0]))
        self[modelName] = self.inst.import(path.join(dbModelsPath, file))
      })

    // Associate DB Models

    require(path.join(dbModelsPath, '_relations.js'))(self)

NGPixel's avatar
NGPixel committed
103 104 105 106 107 108
    // Set init tasks

    let initTasks = {
      // -> Sync DB Schemas
      syncSchemas() {
        return self.inst.sync({
109
          force: false,
110
          logging: log => { WIKI.logger.log('debug', log) }
NGPixel's avatar
NGPixel committed
111 112 113 114
        })
      },
      // -> Set Connection App Name
      setAppName() {
115
        return self.inst.query(`set application_name = 'WIKI.js'`, { raw: true })
NGPixel's avatar
NGPixel committed
116 117 118
      }
    }

119
    let initTasksQueue = (WIKI.IS_MASTER) ? [
NGPixel's avatar
NGPixel committed
120 121 122 123 124 125 126 127
      initTasks.syncSchemas,
      initTasks.setAppName
    ] : [
      initTasks.setAppName
    ]

    // Perform init tasks

128
    this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
129

130
    return this
131 132
  }
}