message.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const Message = require('./schemas/message');
  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 Message.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: messages, totalDocs: total } = results;
  22. return { total: total.toString(), limit, page, messages };
  23. };
  24. const getListById = async (companionId, userId) => {
  25. const messages = await Message.find({
  26. companionId,
  27. owner: userId,
  28. });
  29. return messages;
  30. };
  31. const getById = async (id, userId) => {
  32. const foundMessage = await Message.findById({
  33. _id: id,
  34. owner: userId,
  35. });
  36. return foundMessage;
  37. };
  38. const getLastMessagesList = async (userId) => {
  39. const messages = await Message.find({ owner: userId });
  40. return messages;
  41. };
  42. const getByField = async (number, userId) => {
  43. const message = await Message.findOne({
  44. number,
  45. owner: userId,
  46. });
  47. return message;
  48. };
  49. const add = async (obj) => {
  50. const message = await Message.create(obj);
  51. return message;
  52. };
  53. const remove = async (id, userId) => {
  54. const removedMessage = await Message.findByIdAndRemove({
  55. _id: id,
  56. owner: userId,
  57. });
  58. return removedMessage;
  59. };
  60. module.exports = {
  61. getList,
  62. getListById,
  63. getByField,
  64. getById,
  65. getLastMessagesList,
  66. add,
  67. remove,
  68. };