HttpController.coffee 1.6 KB

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