HttpController.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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("logger-sharelatex");
  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.log({user_id, contact_id}, "adding contact");
  24. return ContactManager.touchContact(user_id, contact_id, function(error) {
  25. if (error != null) { return next(error); }
  26. return ContactManager.touchContact(contact_id, user_id, function(error) {
  27. if (error != null) { return next(error); }
  28. return res.status(204).end();
  29. });
  30. });
  31. },
  32. CONTACT_LIMIT: 50,
  33. getContacts(req, res, next) {
  34. let limit;
  35. let {user_id} = req.params;
  36. if ((req.query != null ? req.query.limit : undefined) != null) {
  37. limit = parseInt(req.query.limit, 10);
  38. } else {
  39. limit = HttpController.CONTACT_LIMIT;
  40. }
  41. limit = Math.min(limit, HttpController.CONTACT_LIMIT);
  42. logger.log({user_id}, "getting contacts");
  43. return ContactManager.getContacts(user_id, function(error, contact_dict) {
  44. if (error != null) { return next(error); }
  45. let contacts = [];
  46. const object = contact_dict || {};
  47. for (user_id in object) {
  48. const data = object[user_id];
  49. contacts.push({
  50. user_id,
  51. n: data.n,
  52. ts: data.ts
  53. });
  54. }
  55. HttpController._sortContacts(contacts);
  56. contacts = contacts.slice(0, limit);
  57. const contact_ids = contacts.map(contact => contact.user_id);
  58. return res.status(200).send({
  59. contact_ids
  60. });
  61. });
  62. },
  63. _sortContacts(contacts) {
  64. return contacts.sort(function(a, b) {
  65. // Sort by decreasing count, descreasing timestamp.
  66. // I.e. biggest count, and most recent at front.
  67. if (a.n > b.n) {
  68. return -1;
  69. } else if (a.n < b.n) {
  70. return 1;
  71. } else {
  72. if (a.ts > b.ts) {
  73. return -1;
  74. } else if (a.ts < b.ts) {
  75. return 1;
  76. } else {
  77. return 0;
  78. }
  79. }
  80. });
  81. }
  82. });