HttpController.coffee 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. ContactManager = require "./ContactManager"
  2. WebApiManager = require "./WebApiManager"
  3. logger = require "logger-sharelatex"
  4. async = require "async"
  5. module.exports = HttpController =
  6. addContact: (req, res, next) ->
  7. {user_id} = req.params
  8. {contact_id} = req.body
  9. if !contact_id? or contact_id == ""
  10. res.status(400).send("contact_id should be a non-blank string")
  11. return
  12. logger.log {user_id, contact_id}, "adding contact"
  13. ContactManager.touchContact user_id, contact_id, (error) ->
  14. return next(error) if error?
  15. ContactManager.touchContact contact_id, user_id, (error) ->
  16. return next(error) if error?
  17. res.status(204).end()
  18. CONTACT_LIMIT: 50
  19. getContacts: (req, res, next) ->
  20. {user_id} = req.params
  21. if req.query?.limit?
  22. limit = parseInt(req.query.limit, 10)
  23. else
  24. limit = HttpController.CONTACT_LIMIT
  25. limit = Math.min(limit, HttpController.CONTACT_LIMIT)
  26. logger.log {user_id}, "getting contacts"
  27. ContactManager.getContacts user_id, (error, contact_dict) ->
  28. return next(error) if error?
  29. contacts = []
  30. for user_id, data of (contact_dict or {})
  31. contacts.push {
  32. user_id: user_id
  33. n: data.n
  34. ts: data.ts
  35. }
  36. HttpController._sortContacts contacts
  37. contacts = contacts.slice(0, limit)
  38. async.mapLimit contacts, 5,
  39. (contact, cb) ->
  40. WebApiManager.getUserDetails contact.user_id, (error, user) ->
  41. return cb(error) if error?
  42. cb null, HttpController._formatUser user
  43. (error, users) ->
  44. return next(error) if error?
  45. res.status(200).send({
  46. contacts: users
  47. })
  48. _sortContacts: (contacts) ->
  49. contacts.sort (a, b) ->
  50. # Sort by decreasing count, descreasing timestamp.
  51. # I.e. biggest count, and most recent at front.
  52. if a.n > b.n
  53. return -1
  54. else if a.n < b.n
  55. return 1
  56. else
  57. if a.ts > b.ts
  58. return -1
  59. else if a.ts < b.ts
  60. return 1
  61. else
  62. return 0
  63. _formatUser: (user) ->
  64. return {
  65. id: user._id
  66. email: user.email
  67. first_name: user.first_name
  68. last_name: user.last_name
  69. }