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.

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