HttpController.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* eslint-disable
  2. camelcase,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS102: Remove unnecessary code created because of implicit returns
  9. * DS207: Consider shorter variations of null checks
  10. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  11. */
  12. let HttpController
  13. const ContactManager = require('./ContactManager')
  14. const logger = require('@overleaf/logger')
  15. module.exports = HttpController = {
  16. addContact(req, res, next) {
  17. const { user_id } = req.params
  18. const { contact_id } = req.body
  19. if (contact_id == null || contact_id === '') {
  20. res.status(400).send('contact_id should be a non-blank string')
  21. return
  22. }
  23. logger.debug({ user_id, contact_id }, 'adding contact')
  24. return ContactManager.touchContact(user_id, contact_id, function (error) {
  25. if (error != null) {
  26. return next(error)
  27. }
  28. return ContactManager.touchContact(contact_id, user_id, function (error) {
  29. if (error != null) {
  30. return next(error)
  31. }
  32. return res.sendStatus(204)
  33. })
  34. })
  35. },
  36. CONTACT_LIMIT: 50,
  37. getContacts(req, res, next) {
  38. let limit
  39. let { user_id } = req.params
  40. if ((req.query != null ? req.query.limit : undefined) != null) {
  41. limit = parseInt(req.query.limit, 10)
  42. } else {
  43. limit = HttpController.CONTACT_LIMIT
  44. }
  45. limit = Math.min(limit, HttpController.CONTACT_LIMIT)
  46. logger.debug({ user_id }, 'getting contacts')
  47. return ContactManager.getContacts(user_id, function (error, contact_dict) {
  48. if (error != null) {
  49. return next(error)
  50. }
  51. let contacts = []
  52. const object = contact_dict || {}
  53. for (user_id in object) {
  54. const data = object[user_id]
  55. contacts.push({
  56. user_id,
  57. n: data.n,
  58. ts: data.ts,
  59. })
  60. }
  61. HttpController._sortContacts(contacts)
  62. contacts = contacts.slice(0, limit)
  63. const contact_ids = contacts.map(contact => contact.user_id)
  64. return res.status(200).send({
  65. contact_ids,
  66. })
  67. })
  68. },
  69. _sortContacts(contacts) {
  70. return contacts.sort(function (a, b) {
  71. // Sort by decreasing count, descreasing timestamp.
  72. // I.e. biggest count, and most recent at front.
  73. if (a.n > b.n) {
  74. return -1
  75. } else if (a.n < b.n) {
  76. return 1
  77. } else {
  78. if (a.ts > b.ts) {
  79. return -1
  80. } else if (a.ts < b.ts) {
  81. return 1
  82. } else {
  83. return 0
  84. }
  85. }
  86. })
  87. },
  88. }