123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- 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 isUser = await ChatModel.getByField(id, userId);
- const isCompanion = await ChatModel.getByField(userId, id);
- const { name, lastName, avatarUrl, color, number } = user;
- if (companion && isUser && isCompanion) {
- 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,
- });
- return res.status(201).json({
- status: 'success',
- code: 201,
- data: newMessage,
- });
- }
- } catch (e) {
- next(e);
- }
- };
- module.exports = {
- listMessages,
- sentMessage,
- listMessagesById,
- };
|