ChatManager.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const async = require('async')
  2. const UserInfoManager = require('../User/UserInfoManager')
  3. const UserInfoController = require('../User/UserInfoController')
  4. const { promisify } = require('@overleaf/promise-utils')
  5. function injectUserInfoIntoThreads(threads, callback) {
  6. // There will be a lot of repitition of user_ids, so first build a list
  7. // of unique ones to perform db look ups on, then use these to populate the
  8. // user fields
  9. let message, thread, threadId, userId
  10. if (callback == null) {
  11. callback = function () {}
  12. }
  13. const userIds = {}
  14. for (threadId in threads) {
  15. thread = threads[threadId]
  16. if (thread.resolved) {
  17. userIds[thread.resolved_by_user_id] = true
  18. }
  19. for (message of Array.from(thread.messages)) {
  20. userIds[message.user_id] = true
  21. }
  22. }
  23. const jobs = []
  24. const users = {}
  25. for (userId in userIds) {
  26. ;(userId =>
  27. jobs.push(cb =>
  28. UserInfoManager.getPersonalInfo(userId, function (error, user) {
  29. if (error != null) return cb(error)
  30. user = UserInfoController.formatPersonalInfo(user)
  31. users[userId] = user
  32. cb()
  33. })
  34. ))(userId)
  35. }
  36. return async.series(jobs, function (error) {
  37. if (error != null) {
  38. return callback(error)
  39. }
  40. for (threadId in threads) {
  41. thread = threads[threadId]
  42. if (thread.resolved) {
  43. thread.resolved_by_user = users[thread.resolved_by_user_id]
  44. }
  45. for (message of Array.from(thread.messages)) {
  46. message.user = users[message.user_id]
  47. }
  48. }
  49. return callback(null, threads)
  50. })
  51. }
  52. module.exports = {
  53. injectUserInfoIntoThreads,
  54. promises: {
  55. injectUserInfoIntoThreads: promisify(injectUserInfoIntoThreads),
  56. },
  57. }