config.js 2.6 KB

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