config.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. try {
  61. for (let key of keys) {
  62. let value = _.get(WIKI.config, key, null)
  63. if (!_.isPlainObject(value)) {
  64. value = { v: value }
  65. }
  66. let affectedRows = await WIKI.db.settings.query().patch({ value }).where('key', key)
  67. if (affectedRows === 0 && value) {
  68. await WIKI.db.settings.query().insert({ key, value })
  69. }
  70. }
  71. } catch (err) {
  72. WIKI.logger.error(`Failed to save configuration to DB: ${err.message}`)
  73. return false
  74. }
  75. return true
  76. }
  77. }