chat.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const Chat = require('./schemas/chat');
  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 Chat.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: chats, totalDocs: total } = results;
  22. return { total: total.toString(), limit, page, chats };
  23. };
  24. const getByField = async (companionId, userId) => {
  25. const chat = await Chat.findOne({
  26. companionId,
  27. owner: userId,
  28. });
  29. return chat;
  30. };
  31. const add = async (obj) => {
  32. const chat = await Chat.create(obj);
  33. return chat;
  34. };
  35. const update = async (id, obj) => {
  36. const chat = await Chat.updateOne({ _id: id }, { ...obj });
  37. return chat;
  38. };
  39. const updateByOwner = async (id, userId, obj) => {
  40. const chat = await Chat.updateOne({ _id: id, owner: userId }, { ...obj });
  41. return chat;
  42. };
  43. module.exports = {
  44. getList,
  45. getByField,
  46. add,
  47. update,
  48. updateByOwner,
  49. };