config.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const fs = require('mz/fs')
  2. const json = require('comment-json')
  3. const typecheck = require('./util/typecheck')
  4. class Config {
  5. async load() {
  6. const jsonStr = await fs.readFile('config.json', 'utf8').catch(() => {
  7. // Make the error more human-friendly
  8. return Promise.reject('Could not read config.json file')
  9. })
  10. try {
  11. this.obj = json.parse(jsonStr)
  12. } catch (err) {
  13. throw `Error parsing config.json (${err.message})`
  14. }
  15. // Sanitize
  16. try {
  17. typecheck(this.obj.database_uri, {type: String}, 'for database_uri')
  18. typecheck(
  19. this.obj.discord_server_id,
  20. {type: String},
  21. 'for discord_server_id'
  22. )
  23. typecheck(
  24. this.obj.discord_emote_store_server_ids,
  25. {type: Array},
  26. 'for discord_emote_store_server_ids'
  27. )
  28. typecheck(
  29. this.obj.discord_bot_tokens,
  30. {type: Array},
  31. 'for discord_bot_tokens'
  32. )
  33. typecheck(this.obj.protected_ids, {type: Array}, 'for protected_ids')
  34. if (this.obj.protected_ids.length === 0)
  35. throw new TypeError('Please add at least one ID to protected_ids')
  36. typecheck(this.obj.skip_cleanup, {type: Boolean}, 'for skip_cleanup')
  37. } catch (err) {
  38. throw 'Error in config.json:\n' + err.message // It's human-readable!
  39. }
  40. }
  41. get(key) {
  42. if (!this.obj) {
  43. throw new Error('Config not yet loaded')
  44. }
  45. return this.obj[key]
  46. }
  47. }
  48. module.exports = new Config()