contact.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const Contact = require('./schemas/contact');
  2. const getList = async (
  3. userId,
  4. { sortBy, sortByDesc, filter, limit = '500', 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: '_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 getByField = async (number, userId) => {
  32. const contact = await Contact.findOne({
  33. number,
  34. owner: userId,
  35. });
  36. return contact;
  37. };
  38. const add = async (obj) => {
  39. const contact = await Contact.create(obj);
  40. return contact;
  41. };
  42. const remove = async (id, userId) => {
  43. const removedContact = await Contact.findByIdAndRemove({
  44. _id: id,
  45. owner: userId,
  46. });
  47. return removedContact;
  48. };
  49. module.exports = {
  50. getList,
  51. getByField,
  52. getById,
  53. add,
  54. remove,
  55. };