ContactController.mjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import SessionManager from '../Authentication/SessionManager.mjs'
  2. import ContactManager from './ContactManager.mjs'
  3. import UserGetter from '../User/UserGetter.mjs'
  4. import Modules from '../../infrastructure/Modules.mjs'
  5. import { expressify } from '@overleaf/promise-utils'
  6. function _formatContact(contact) {
  7. return {
  8. id: contact._id?.toString(),
  9. email: contact.email || '',
  10. first_name: contact.first_name || '',
  11. last_name: contact.last_name || '',
  12. type: 'user',
  13. }
  14. }
  15. async function getContacts(req, res) {
  16. const userId = SessionManager.getLoggedInUserId(req.session)
  17. const contactIds = await ContactManager.promises.getContactIds(userId, {
  18. limit: 50,
  19. })
  20. let contacts = await UserGetter.promises.getUsers(contactIds, {
  21. email: 1,
  22. first_name: 1,
  23. last_name: 1,
  24. holdingAccount: 1,
  25. })
  26. // UserGetter.getUsers may not preserve order so put them back in order
  27. const positions = {}
  28. for (let i = 0; i < contactIds.length; i++) {
  29. const contactId = contactIds[i]
  30. positions[contactId] = i
  31. }
  32. contacts.sort(
  33. (a, b) => positions[a._id?.toString()] - positions[b._id?.toString()]
  34. )
  35. // Don't count holding accounts to discourage users from repeating mistakes (mistyped or wrong emails, etc)
  36. contacts = contacts.filter(c => !c.holdingAccount)
  37. contacts = contacts.map(_formatContact)
  38. const additionalContacts = await Modules.promises.hooks.fire(
  39. 'getContacts',
  40. userId,
  41. contacts
  42. )
  43. contacts = contacts.concat(...(additionalContacts || []))
  44. return res.json({
  45. contacts,
  46. })
  47. }
  48. export default {
  49. getContacts: expressify(getContacts),
  50. }