1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- const ChatModel = require('../model/chat');
- const UserModel = require('../model/user');
- const listChats = async (req, res, next) => {
- try {
- const userId = req.user.id;
- const chats = await ChatModel.getList(userId, req.query);
- return res.json({
- status: 'success',
- code: 200,
- data: {
- ...chats,
- },
- });
- } catch (e) {
- next(e);
- }
- };
- const startChat = async (req, res, next) => {
- try {
- const id = req.body.id;
- 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, online } = companion;
- const {
- name: Name,
- lastName: LastName,
- avatarUrl: AvatarUrl,
- color: Color,
- online: Online,
- } = user;
- if (companion && (isUser || isCompanion)) {
- await ChatModel.update(isUser._id, {
- name,
- lastName,
- avatarUrl,
- color,
- online,
- });
- await ChatModel.update(isCompanion._id, {
- name: Name,
- lastName: LastName,
- avatarUrl: AvatarUrl,
- color: Color,
- online: Online,
- });
- const updatedChat = await ChatModel.getByField(id, userId);
- return res.status(200).json({
- status: 'success',
- code: 200,
- data: updatedChat,
- });
- }
- if (companion && !isUser && !isCompanion) {
- const newChat = await ChatModel.add({
- name,
- lastName,
- avatarUrl,
- color,
- online,
- companionId: id,
- owner: userId,
- });
- await ChatModel.add({
- name: Name,
- lastName: LastName,
- avatarUrl: AvatarUrl,
- color: Color,
- online: Online,
- companionId: userId,
- owner: id,
- });
- return res.status(201).json({
- status: 'success',
- code: 201,
- data: newChat,
- });
- }
- } catch (e) {
- next(e);
- }
- };
- module.exports = {
- listChats,
- startChat,
- };
|