const Chat = require('./schemas/chat'); const getList = async ( userId, { sortBy, sortByDesc, filter, limit = '500', page = '1', sub } ) => { const options = { owner: userId }; if (sub) options.subscription = { $all: [sub] }; const results = await Chat.paginate(options, { limit, page, sort: { ...(sortBy ? { [`${sortBy}`]: 1 } : {}), ...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}), }, select: filter ? filter.split('|').join(' ') : '', populate: { path: 'owner', select: '_id', }, }); const { docs: chats, totalDocs: total } = results; return { total: total.toString(), limit, page, chats }; }; const getByField = async (companionId, userId) => { const chat = await Chat.findOne({ companionId, owner: userId, }); return chat; }; const add = async (obj) => { const chat = await Chat.create(obj); return chat; }; const remove = async (id, userId) => { const removedChat = await Chat.findByIdAndRemove({ _id: id, owner: userId, }); return removedChat; }; const update = async (id, userId, obj) => { const chat = await Chat.updateOne({ _id: id, owner: userId }, { ...obj }); return chat; }; const updateCompanionsChat = async (companionId, obj) => { const chats = await Chat.updateMany({ companionId }, { ...obj }); return chats; }; module.exports = { getList, getByField, add, remove, update, updateCompanionsChat, };