message.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. const Message = require('./schemas/message');
  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 Message.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: messages, totalDocs: total } = results;
  21. return { total: total.toString(), limit, page, messages };
  22. };
  23. const getById = async (id, userId) => {
  24. const foundMessage = await Message.findById({
  25. _id: id,
  26. owner: userId,
  27. });
  28. return foundMessage;
  29. };
  30. const getByField = async (number, userId) => {
  31. const message = await Message.findOne({
  32. number,
  33. owner: userId,
  34. });
  35. return message;
  36. };
  37. const add = async (obj) => {
  38. const message = await Message.create(obj);
  39. return message;
  40. };
  41. const remove = async (id, userId) => {
  42. const removedMessage = await Message.findByIdAndRemove({
  43. _id: id,
  44. owner: userId,
  45. });
  46. return removedMessage;
  47. };
  48. const removeByFields = async (companionId, idTime, userId) => {
  49. const removedMessage = await Message.findOne({
  50. companionId,
  51. idTime,
  52. owner: userId,
  53. }).deleteOne();
  54. return removedMessage;
  55. };
  56. const removeAll = async (companionId, userId) => {
  57. const removedAllMessages = await Message.deleteMany({
  58. companionId,
  59. owner: userId,
  60. });
  61. return removedAllMessages;
  62. };
  63. const updateCompanionsMessages = async (companionId, obj) => {
  64. const messages = await Message.updateMany({ companionId }, { ...obj });
  65. return messages;
  66. };
  67. const updateOwnerMessages = async (options, obj) => {
  68. const messages = await Message.updateMany({ ...options }, { ...obj });
  69. return messages;
  70. };
  71. module.exports = {
  72. getList,
  73. getByField,
  74. getById,
  75. add,
  76. remove,
  77. removeByFields,
  78. removeAll,
  79. updateCompanionsMessages,
  80. updateOwnerMessages,
  81. };