SystemMessageManager.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* eslint-disable
  2. n/handle-callback-err,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS102: Remove unnecessary code created because of implicit returns
  9. * DS207: Consider shorter variations of null checks
  10. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  11. */
  12. let SystemMessageManager
  13. const { SystemMessage } = require('../../models/SystemMessage')
  14. const {
  15. addRequiredCleanupHandlerBeforeDrainingConnections,
  16. } = require('../../infrastructure/GracefulShutdown')
  17. module.exports = SystemMessageManager = {
  18. getMessages(callback) {
  19. if (callback == null) {
  20. callback = function () {}
  21. }
  22. callback(null, this._cachedMessages)
  23. },
  24. getMessagesFromDB(callback) {
  25. if (callback == null) {
  26. callback = function () {}
  27. }
  28. return SystemMessage.find({}, callback)
  29. },
  30. clearMessages(callback) {
  31. if (callback == null) {
  32. callback = function () {}
  33. }
  34. return SystemMessage.deleteMany({}, callback)
  35. },
  36. createMessage(content, callback) {
  37. if (callback == null) {
  38. callback = function () {}
  39. }
  40. const message = new SystemMessage({ content })
  41. return message.save(callback)
  42. },
  43. refreshCache() {
  44. this.getMessagesFromDB((error, messages) => {
  45. if (!error) {
  46. this._cachedMessages = messages
  47. }
  48. })
  49. },
  50. }
  51. const CACHE_TIMEOUT = 10 * 1000 * (Math.random() + 2) // 20-30 seconds
  52. SystemMessageManager.refreshCache()
  53. const intervalHandle = setInterval(
  54. () => SystemMessageManager.refreshCache(),
  55. CACHE_TIMEOUT
  56. )
  57. addRequiredCleanupHandlerBeforeDrainingConnections(
  58. 'update system messages',
  59. () => {
  60. clearInterval(intervalHandle)
  61. }
  62. )