SystemMessageManager.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const { SystemMessage } = require('../../models/SystemMessage')
  2. const {
  3. addRequiredCleanupHandlerBeforeDrainingConnections,
  4. } = require('../../infrastructure/GracefulShutdown')
  5. const { callbackifyAll } = require('@overleaf/promise-utils')
  6. const SystemMessageManager = {
  7. getMessages() {
  8. return this._cachedMessages
  9. },
  10. async getMessagesFromDB() {
  11. return await SystemMessage.find({}).exec()
  12. },
  13. async clearMessages() {
  14. await SystemMessage.deleteMany({}).exec()
  15. },
  16. async createMessage(content) {
  17. const message = new SystemMessage({ content })
  18. await message.save()
  19. },
  20. async refreshCache() {
  21. const messages = await this.getMessagesFromDB()
  22. this._cachedMessages = messages
  23. },
  24. }
  25. const CACHE_TIMEOUT = 10 * 1000 * (Math.random() + 2) // 20-30 seconds
  26. SystemMessageManager.refreshCache()
  27. const intervalHandle = setInterval(
  28. () => SystemMessageManager.refreshCache(),
  29. CACHE_TIMEOUT
  30. )
  31. addRequiredCleanupHandlerBeforeDrainingConnections(
  32. 'update system messages',
  33. () => {
  34. clearInterval(intervalHandle)
  35. }
  36. )
  37. module.exports = {
  38. getMessages: SystemMessageManager.getMessages.bind(SystemMessageManager),
  39. ...callbackifyAll(SystemMessageManager, { without: ['getMessages'] }),
  40. promises: SystemMessageManager,
  41. }