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.

105 lines
2.5 KiB

  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. * @param {Array} subsets Array of subsets to load
  45. * @returns Promise
  46. */
  47. async loadFromDb(subsets) {
  48. if (!_.isArray(subsets) || subsets.length === 0) {
  49. subsets = wiki.data.configNamespaces
  50. }
  51. let results = await wiki.db.Setting.findAll({
  52. attributes: ['key', 'config'],
  53. where: {
  54. key: {
  55. $in: subsets
  56. }
  57. }
  58. })
  59. if (_.isArray(results) && results.length === subsets.length) {
  60. results.forEach(result => {
  61. wiki.config[result.key] = result.config
  62. })
  63. return true
  64. } else {
  65. wiki.logger.warn('DB Configuration is empty or incomplete.')
  66. return false
  67. }
  68. },
  69. /**
  70. * Save config to DB
  71. *
  72. * @param {Array} subsets Array of subsets to save
  73. * @returns Promise
  74. */
  75. async saveToDb(subsets) {
  76. if (!_.isArray(subsets) || subsets.length === 0) {
  77. subsets = wiki.data.configNamespaces
  78. }
  79. try {
  80. for (let set of subsets) {
  81. await wiki.db.Setting.upsert({
  82. key: set,
  83. config: _.get(wiki.config, set, {})
  84. })
  85. }
  86. } catch (err) {
  87. wiki.logger.error(`Failed to save configuration to DB: ${err.message}`)
  88. return false
  89. }
  90. return true
  91. }
  92. }