You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.6 KiB

  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. appconfig.public = (appconfig.public === true || _.toLower(appconfig.public) === 'true')
  45. WIKI.config = appconfig
  46. WIKI.data = appdata
  47. WIKI.version = require(path.join(WIKI.ROOTPATH, 'package.json')).version
  48. },
  49. /**
  50. * Load config from DB
  51. */
  52. async loadFromDb() {
  53. let conf = await WIKI.models.settings.getConfig()
  54. if (conf) {
  55. WIKI.config = _.defaultsDeep(conf, WIKI.config)
  56. } else {
  57. WIKI.logger.warn('DB Configuration is empty or incomplete. Switching to Setup mode...')
  58. WIKI.config.setup = true
  59. }
  60. },
  61. /**
  62. * Save config to DB
  63. *
  64. * @param {Array} keys Array of keys to save
  65. * @returns Promise
  66. */
  67. async saveToDb(keys) {
  68. try {
  69. for (let key of keys) {
  70. let value = _.get(WIKI.config, key, null)
  71. if (!_.isPlainObject(value)) {
  72. value = { v: value }
  73. }
  74. let affectedRows = await WIKI.models.settings.query().patch({ value }).where('key', key)
  75. if (affectedRows === 0 && value) {
  76. await WIKI.models.settings.query().insert({ key, value })
  77. }
  78. }
  79. } catch (err) {
  80. WIKI.logger.error(`Failed to save configuration to DB: ${err.message}`)
  81. return false
  82. }
  83. return true
  84. }
  85. }