HttpController.js 2.3 KB

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