chat.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. module.exports = {
  40. getList,
  41. getByField,
  42. add,
  43. update,
  44. };