1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- const MessageModel = require('../model/message');
- const UserModel = require('../model/user');
- const ChatModel = require('../model/chat');
- const listMessages = async (req, res, next) => {
- try {
- const userId = req.user.id;
- const messages = await MessageModel.getList(userId, req.query);
- return res.json({
- status: 'success',
- code: 200,
- data: {
- ...messages,
- },
- });
- } catch (e) {
- next(e);
- }
- };
- const listMessagesById = async (req, res, next) => {
- try {
- const userId = req.user.id;
- const companionId = req.params.companionId;
- const messages = await MessageModel.getListById(companionId, userId);
- return res.json({
- status: 'success',
- code: 200,
- data: [...messages],
- });
- } catch (e) {
- next(e);
- }
- };
- const sentMessage = async (req, res, next) => {
- try {
- const { id, message } = req.body;
- const user = req.user;
- const userId = user.id;
- const companion = await UserModel.findById(id);
- const isChat = await ChatModel.getByField(id, userId);
- const isCompanionChat = await ChatModel.getByField(userId, id);
- const { name, lastName, avatarUrl, color, number } = user;
- if (companion && isChat && isCompanionChat) {
- const newMessage = await MessageModel.add({
- message,
- name,
- lastName,
- avatarUrl,
- color,
- number,
- companionId: id,
- owner: userId,
- });
- await MessageModel.add({
- message,
- name,
- lastName,
- avatarUrl,
- color,
- number,
- companionId: userId,
- owner: id,
- });
- const { total } = await MessageModel.getList(userId, {});
- await ChatModel.update(isChat._id, { total });
- const { total: Total } = await MessageModel.getList(id, {});
- await ChatModel.update(isCompanionChat._id, { total: Total });
- return res.status(201).json({
- status: 'success',
- code: 201,
- data: newMessage,
- });
- }
- } catch (e) {
- next(e);
- }
- };
- module.exports = {
- listMessages,
- sentMessage,
- listMessagesById,
- };
|