freechat/freechat-client/src/config.js
shockrah 68e22e1b38 - removing uninportant things
+ messages module was for some reason still using legacy url generation(fixed that)
+ switching types to use bigint since everything is u64/i64 on the backend
2021-04-14 23:00:39 -07:00

78 lines
2.0 KiB
JavaScript

const { ArgumentParser } = require('argparse')
const fs = require('fs').promises
const syncFs = require('fs')
// required because freechat by default uses i64/u64 in json payloads
// timestamps will get especially rekt'd if we don't parse things correctly
const JSONBig = require('json-bigint')
class Config {
/**
*
* @param {String} path path to config on startup
* @param {Object} data Contains actual config data
*/
constructor(path, data) {
this.path = path
this.data = data
}
async write_disk() {
const str = JSONBig.stringify(this.data, null, 4)
await fs.writeFile(this.path, str)
}
}
exports.Config = Config
/**
* Gets the config data off disk
* @param {ArgumentParset} parser
* @returns {Config}
*/
exports.from_cli_parser = function(parser) {
const args = parser.parse_args()
const defaultpath = `${process.env.HOME || process.env.USERPROFILE}/.config/freechat/config.json`
// We'll just assume that the config is there as per the installation process
const path = (args['config']) ? args['config'] : defaultpath
let ret = new Config(path, {})
// Allow errors from here to bubble up instead of handling them
fs.readFile(path).then(file => {
const json = JSONBig.parse(file)
for(const key of Object.keys(json)) {
ret.data[key] = json[key]
}
})
.catch(err => console.error(err))
return ret
}
/**
* Updates the config with the new object data
* Called from node's main process
*
* @param {Config} config new config data to write
* @param {String} path | set to 'default' if we're using $HOME/.config/freechat/config.json
* Set this to anything else to write changes to that specified path
*/
exports.update_file = function(config, path='default') {
if (path == 'default') {
path = `${process.env.HOME || process.env.USERPROFILE}/.config/freechat/config.json`
} else {
path = path
}
const data = JSON.stringify(config, null, 2)
fs.writeFile(path, data, function(err) {
if(err) { console.error(err) }
else { console.log('fine') }
})
}