123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- const Message = require('./schemas/message');
- const getList = async (
- options,
- { sortBy, sortByDesc, filter, limit = '500', page = '1', sub }
- ) => {
- if (sub) options.subscription = { $all: [sub] };
- const results = await Message.paginate(options, {
- limit,
- page,
- sort: {
- ...(sortBy ? { [`${sortBy}`]: 1 } : {}),
- ...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}),
- },
- select: filter ? filter.split('|').join(' ') : '',
- populate: {
- path: 'owner',
- select: '_id',
- },
- });
- const { docs: messages, totalDocs: total } = results;
- return { total: total.toString(), limit, page, messages };
- };
- const getById = async (id, userId) => {
- const foundMessage = await Message.findById({
- _id: id,
- owner: userId,
- });
- return foundMessage;
- };
- const getByField = async (number, userId) => {
- const message = await Message.findOne({
- number,
- owner: userId,
- });
- return message;
- };
- const add = async (obj) => {
- const message = await Message.create(obj);
- return message;
- };
- const remove = async (id, userId) => {
- const removedMessage = await Message.findByIdAndRemove({
- _id: id,
- owner: userId,
- });
- return removedMessage;
- };
- const removeByFields = async (companionId, idTime, userId) => {
- const removedMessage = await Message.findOne({
- companionId,
- idTime,
- owner: userId,
- }).deleteOne();
- return removedMessage;
- };
- const findByFieldsAndUpdate = async (companionId, idTime, userId, body) => {
- const message = await Message.findOne({
- companionId,
- idTime,
- owner: userId,
- }).updateOne({ ...body });
- return message;
- };
- const removeAll = async (companionId, userId) => {
- const removedAllMessages = await Message.deleteMany({
- companionId,
- owner: userId,
- });
- return removedAllMessages;
- };
- const updateCompanionsMessages = async (companionId, obj) => {
- const messages = await Message.updateMany({ companionId }, { ...obj });
- return messages;
- };
- const updateOwnerMessages = async (options, obj) => {
- const messages = await Message.updateMany({ ...options }, { ...obj });
- return messages;
- };
- const updateMessage = async (id, userId, body) => {
- return await Message.findByIdAndUpdate(
- { _id: id, owner: userId },
- { ...body },
- { new: true }
- );
- };
- module.exports = {
- getList,
- getByField,
- getById,
- add,
- remove,
- removeByFields,
- findByFieldsAndUpdate,
- removeAll,
- updateCompanionsMessages,
- updateOwnerMessages,
- updateMessage,
- };
|