contact.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const Contact = require("./schemas/contact");
  2. const getList = async (
  3. userId,
  4. { sortBy, sortByDesc, filter, limit = "5", page = "1", sub }
  5. ) => {
  6. const options = { owner: userId };
  7. if (sub) options.subscription = { $all: [sub] };
  8. const results = await Contact.paginate(options, {
  9. limit,
  10. page,
  11. sort: {
  12. ...(sortBy ? { [`${sortBy}`]: 1 } : {}),
  13. ...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}),
  14. },
  15. select: filter ? filter.split("|").join(" ") : "",
  16. populate: {
  17. path: "owner",
  18. select: "email password subscription token -_id",
  19. },
  20. });
  21. const { docs: contacts, totalDocs: total } = results;
  22. return { total: total.toString(), limit, page, contacts };
  23. };
  24. const getById = async (id, userId) => {
  25. const foundContact = await Contact.findById({
  26. _id: id,
  27. owner: userId,
  28. });
  29. return foundContact;
  30. };
  31. const add = async (obj) => {
  32. const contact = await Contact.create(obj);
  33. return contact;
  34. };
  35. const remove = async (id, userId) => {
  36. const removedContact = await Contact.findByIdAndRemove({
  37. _id: id,
  38. owner: userId,
  39. });
  40. return removedContact;
  41. };
  42. const update = async (id, userId, body) => {
  43. const contact = await Contact.findByIdAndUpdate(
  44. { _id: id, owner: userId },
  45. { ...body },
  46. { new: true }
  47. );
  48. return contact;
  49. };
  50. module.exports = {
  51. getList,
  52. getById,
  53. add,
  54. remove,
  55. update,
  56. };