db.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict'
  2. /* global wiki */
  3. const fs = require('fs')
  4. const path = require('path')
  5. const _ = require('lodash')
  6. const Promise = require('bluebird')
  7. /**
  8. * PostgreSQL DB module
  9. */
  10. module.exports = {
  11. Sequelize: require('sequelize'),
  12. /**
  13. * Initialize DB
  14. *
  15. * @return {Object} DB instance
  16. */
  17. init() {
  18. let self = this
  19. let dbModelsPath = path.join(wiki.SERVERPATH, 'models')
  20. // Define Sequelize instance
  21. self.inst = new self.Sequelize(wiki.config.db.db, wiki.config.db.user, wiki.config.db.pass, {
  22. host: wiki.config.db.host,
  23. port: wiki.config.db.port,
  24. dialect: 'postgres',
  25. pool: {
  26. max: 10,
  27. min: 0,
  28. idle: 10000
  29. },
  30. logging: false
  31. })
  32. // Attempt to connect and authenticate to DB
  33. self.inst.authenticate().then(() => {
  34. wiki.logger.info('Connected to PostgreSQL database.')
  35. }).catch(err => {
  36. wiki.logger.error('Failed to connect to MongoDB instance.')
  37. return err
  38. })
  39. // Load DB Models
  40. fs
  41. .readdirSync(dbModelsPath)
  42. .filter(function (file) {
  43. return (file.indexOf('.') !== 0 && file.indexOf('_') !== 0)
  44. })
  45. .forEach(function (file) {
  46. let modelName = _.upperFirst(_.camelCase(_.split(file, '.')[0]))
  47. self[modelName] = self.inst.import(path.join(dbModelsPath, file))
  48. })
  49. // Associate DB Models
  50. require(path.join(dbModelsPath, '_relations.js'))(self)
  51. // Sync DB
  52. self.onReady = (wiki.IS_MASTER) ? self.inst.sync({
  53. force: false,
  54. logging: false
  55. }) : Promise.resolve()
  56. return self
  57. }
  58. }