SystemMessageManager.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. * DS207: Consider shorter variations of null checks
  9. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  10. */
  11. let SystemMessageManager
  12. const { SystemMessage } = require('../../models/SystemMessage')
  13. const {
  14. addRequiredCleanupHandlerBeforeDrainingConnections,
  15. } = require('../../infrastructure/GracefulShutdown')
  16. module.exports = SystemMessageManager = {
  17. getMessages(callback) {
  18. if (callback == null) {
  19. callback = function () {}
  20. }
  21. callback(null, this._cachedMessages)
  22. },
  23. getMessagesFromDB(callback) {
  24. if (callback == null) {
  25. callback = function () {}
  26. }
  27. SystemMessage.find({}, callback)
  28. },
  29. clearMessages(callback) {
  30. if (callback == null) {
  31. callback = function () {}
  32. }
  33. SystemMessage.deleteMany({}, callback)
  34. },
  35. createMessage(content, callback) {
  36. if (callback == null) {
  37. callback = function () {}
  38. }
  39. const message = new SystemMessage({ content })
  40. message.save(callback)
  41. },
  42. refreshCache() {
  43. this.getMessagesFromDB((error, messages) => {
  44. if (!error) {
  45. this._cachedMessages = messages
  46. }
  47. })
  48. },
  49. }
  50. const CACHE_TIMEOUT = 10 * 1000 * (Math.random() + 2) // 20-30 seconds
  51. SystemMessageManager.refreshCache()
  52. const intervalHandle = setInterval(
  53. () => SystemMessageManager.refreshCache(),
  54. CACHE_TIMEOUT
  55. )
  56. addRequiredCleanupHandlerBeforeDrainingConnections(
  57. 'update system messages',
  58. () => {
  59. clearInterval(intervalHandle)
  60. }
  61. )