contact.js 1.4 KB

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