chat.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 remove = async (id, userId) => {
  36. const removedChat = await Chat.findByIdAndRemove({
  37. _id: id,
  38. owner: userId,
  39. });
  40. return removedChat;
  41. };
  42. const update = async (id, userId, obj) => {
  43. const chat = await Chat.updateOne({ _id: id, owner: userId }, { ...obj });
  44. return chat;
  45. };
  46. const updateCompanionsChat = async (companionId, online) => {
  47. const chats = await Chat.updateMany({ companionId }, { online });
  48. return chats;
  49. };
  50. module.exports = {
  51. getList,
  52. getByField,
  53. add,
  54. remove,
  55. update,
  56. updateCompanionsChat,
  57. };