config.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const path = require('path')
  2. const fs = require('mz/fs')
  3. const json = require('comment-json')
  4. const typecheck = require('./util/typecheck')
  5. class Config {
  6. async load() {
  7. const jsonStr = await fs.readFile('config.json', 'utf8')
  8. .catch(err => {
  9. // Make the error more human-friendly
  10. return Promise.reject('Could not read config.json file')
  11. })
  12. try {
  13. this.obj = json.parse(jsonStr)
  14. } catch (err) {
  15. throw `Error parsing config.json (${err.message})`
  16. }
  17. // Sanitize
  18. try {
  19. typecheck(this.obj.database_uri, {type: String}, 'for database_uri')
  20. typecheck(this.obj.discord_server_id, {type: String}, 'for discord_server_id')
  21. typecheck(this.obj.discord_bot_tokens, {type: Array}, 'for discord_bot_tokens')
  22. } catch (err) {
  23. throw 'Error in config.json:\n' + err.message // It's human-readable!
  24. }
  25. }
  26. get(key) {
  27. if (!this.obj) {
  28. throw new Error('Config not yet loaded')
  29. }
  30. return this.obj[key]
  31. }
  32. }
  33. module.exports = new Config()