wiki/server/core/config.js

90 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-04-02 18:56:47 -05:00
const _ = require('lodash')
2017-05-14 20:20:40 -05:00
const cfgHelper = require('../helpers/config')
const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml')
/* global WIKI */
2017-07-29 16:33:08 -05:00
module.exports = {
/**
* Load root config from disk
*/
init() {
let confPaths = {
config: path.join(WIKI.ROOTPATH, 'config.yml'),
data: path.join(WIKI.SERVERPATH, 'app/data.yml'),
dataRegex: path.join(WIKI.SERVERPATH, 'app/regex.js')
2017-07-29 16:33:08 -05:00
}
let appconfig = {}
let appdata = {}
try {
appconfig = yaml.safeLoad(
cfgHelper.parseConfigValue(
fs.readFileSync(confPaths.config, 'utf8')
)
2017-05-13 13:44:04 -05:00
)
2017-07-29 16:33:08 -05:00
appdata = yaml.safeLoad(fs.readFileSync(confPaths.data, 'utf8'))
appdata.regex = require(confPaths.dataRegex)
} catch (ex) {
console.error(ex)
process.exit(1)
}
2017-04-02 18:56:47 -05:00
2017-07-29 16:33:08 -05:00
// Merge with defaults
2017-04-02 18:56:47 -05:00
2017-07-29 16:33:08 -05:00
appconfig = _.defaultsDeep(appconfig, appdata.defaults.config)
2017-04-02 18:56:47 -05:00
2017-07-29 16:33:08 -05:00
if (appconfig.port < 1) {
appconfig.port = process.env.PORT || 80
}
2017-04-18 19:31:07 -05:00
2017-09-10 00:41:22 -05:00
appconfig.public = (appconfig.public === true || _.toLower(appconfig.public) === 'true')
WIKI.config = appconfig
WIKI.data = appdata
WIKI.version = require(path.join(WIKI.ROOTPATH, 'package.json')).version
2017-07-29 16:33:08 -05:00
},
/**
* Load config from DB
*/
2018-05-28 13:46:55 -05:00
async loadFromDb() {
let conf = await WIKI.db.settings.getConfig()
if (conf) {
WIKI.config = _.defaultsDeep(conf, WIKI.config)
2017-12-16 22:41:16 -06:00
} else {
2018-05-28 13:46:55 -05:00
WIKI.logger.warn('DB Configuration is empty or incomplete. Switching to Setup mode...')
WIKI.config.setup = true
2017-12-16 22:41:16 -06:00
}
},
/**
* Save config to DB
*
2018-05-28 13:46:55 -05:00
* @param {Array} keys Array of keys to save
2017-12-16 22:41:16 -06:00
* @returns Promise
*/
2018-05-28 13:46:55 -05:00
async saveToDb(keys) {
let trx = await WIKI.db.Objection.transaction.start(WIKI.db.knex)
2017-12-16 22:41:16 -06:00
try {
2018-05-28 13:46:55 -05:00
for (let key of keys) {
const value = _.get(WIKI.config, key, null)
let affectedRows = await WIKI.db.settings.query(trx).patch({ value }).where('key', key)
if (affectedRows === 0 && value) {
await WIKI.db.settings.query(trx).insert({ key, value })
}
2017-07-29 16:33:08 -05:00
}
await trx.commit()
2017-12-16 22:41:16 -06:00
} catch (err) {
await trx.rollback(err)
WIKI.logger.error(`Failed to save configuration to DB: ${err.message}`)
2017-12-16 22:41:16 -06:00
return false
}
return true
2017-04-02 18:56:47 -05:00
}
}