config.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const _ = require('lodash')
  2. const cfgHelper = require('../helpers/config')
  3. const fs = require('fs')
  4. const path = require('path')
  5. const yaml = require('js-yaml')
  6. /* global WIKI */
  7. module.exports = {
  8. /**
  9. * Load root config from disk
  10. */
  11. init() {
  12. let confPaths = {
  13. config: path.join(WIKI.ROOTPATH, 'config.yml'),
  14. data: path.join(WIKI.SERVERPATH, 'app/data.yml'),
  15. dataRegex: path.join(WIKI.SERVERPATH, 'app/regex.js')
  16. }
  17. let appconfig = {}
  18. let appdata = {}
  19. try {
  20. appconfig = yaml.safeLoad(
  21. cfgHelper.parseConfigValue(
  22. fs.readFileSync(confPaths.config, 'utf8')
  23. )
  24. )
  25. appdata = yaml.safeLoad(fs.readFileSync(confPaths.data, 'utf8'))
  26. appdata.regex = require(confPaths.dataRegex)
  27. } catch (ex) {
  28. console.error(ex)
  29. process.exit(1)
  30. }
  31. // Merge with defaults
  32. appconfig = _.defaultsDeep(appconfig, appdata.defaults.config)
  33. if (appconfig.port < 1) {
  34. appconfig.port = process.env.PORT || 80
  35. }
  36. appconfig.public = (appconfig.public === true || _.toLower(appconfig.public) === 'true')
  37. WIKI.config = appconfig
  38. WIKI.data = appdata
  39. WIKI.version = require(path.join(WIKI.ROOTPATH, 'package.json')).version
  40. },
  41. /**
  42. * Load config from DB
  43. */
  44. async loadFromDb() {
  45. let conf = await WIKI.db.settings.getConfig()
  46. if (conf) {
  47. WIKI.config = _.defaultsDeep(conf, WIKI.config)
  48. } else {
  49. WIKI.logger.warn('DB Configuration is empty or incomplete. Switching to Setup mode...')
  50. WIKI.config.setup = true
  51. }
  52. },
  53. /**
  54. * Save config to DB
  55. *
  56. * @param {Array} keys Array of keys to save
  57. * @returns Promise
  58. */
  59. async saveToDb(keys) {
  60. let trx = await WIKI.db.Objection.transaction.start(WIKI.db.knex)
  61. try {
  62. for (let key of keys) {
  63. const value = _.get(WIKI.config, key, null)
  64. let affectedRows = await WIKI.db.settings.query(trx).patch({ value }).where('key', key)
  65. if (affectedRows === 0 && value) {
  66. await WIKI.db.settings.query(trx).insert({ key, value })
  67. }
  68. }
  69. await trx.commit()
  70. } catch (err) {
  71. await trx.rollback(err)
  72. WIKI.logger.error(`Failed to save configuration to DB: ${err.message}`)
  73. return false
  74. }
  75. return true
  76. }
  77. }