config.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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_emote_store_server_ids, {type: Array}, 'for discord_emote_store_server_ids')
  22. typecheck(this.obj.discord_bot_tokens, {type: Array}, 'for discord_bot_tokens')
  23. typecheck(this.obj.protected_ids, {type: Array}, 'for protected_ids')
  24. if (this.obj.protected_ids.length === 0) throw new TypeError('Please add at least one ID to protected_ids')
  25. typecheck(this.obj.skip_cleanup, {type: Boolean}, 'for skip_cleanup')
  26. } catch (err) {
  27. throw 'Error in config.json:\n' + err.message // It's human-readable!
  28. }
  29. }
  30. get(key) {
  31. if (!this.obj) {
  32. throw new Error('Config not yet loaded')
  33. }
  34. return this.obj[key]
  35. }
  36. }
  37. module.exports = new Config()