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.

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