config.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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.settings.query().select(['key', 'value']).whereIn('key', subsets)
  52. if (_.isArray(results) && results.length === subsets.length) {
  53. results.forEach(result => {
  54. WIKI.config[result.key] = result.value
  55. })
  56. return true
  57. } else {
  58. WIKI.logger.warn('DB Configuration is empty or incomplete.')
  59. return false
  60. }
  61. },
  62. /**
  63. * Save config to DB
  64. *
  65. * @param {Array} subsets Array of subsets to save
  66. * @returns Promise
  67. */
  68. async saveToDb(subsets) {
  69. if (!_.isArray(subsets) || subsets.length === 0) {
  70. subsets = WIKI.data.configNamespaces
  71. }
  72. let trx = await WIKI.db.Objection.transaction.start(WIKI.db.knex)
  73. try {
  74. for (let set of subsets) {
  75. console.info(set)
  76. await WIKI.db.settings.query(trx).patch({
  77. value: _.get(WIKI.config, set, {})
  78. }).where('key', set)
  79. }
  80. await trx.commit()
  81. } catch (err) {
  82. await trx.rollback(err)
  83. WIKI.logger.error(`Failed to save configuration to DB: ${err.message}`)
  84. return false
  85. }
  86. return true
  87. }
  88. }