Untitled
// import const Notification = require('../Models/notificationModel.js'); const Socket = require('../socket/socketIndex.js'); // function exports.createNewChat = catchAsync(async (req, res, next) => { const { content, id } = req.body; if (!content) { return next(new AppError('message is require', 400)); } if (!id) { return next(new AppError('user is require', 400)); } const session = await mongoose.startSession(); try { session.startTransaction(); const user = await User.findOne({ _id: id }); const retailer = await Retailer.findOne({ _id: user.profile }); const salesMan = await getRandomSalesMan(retailer.province, retailer._id, next); const chat = await Chat.find({ retailer: retailer._id, sales_man: salesMan._id }); if (chat.length > 0) { const message = await Message.create([{ message: content, sender: retailer._id, receiver: salesMan._id }], { session }); await Chat.updateOne({ _id: chat[0]._id }, { $push: { messages: message[0]._id } }, { session }); } else { const newChat = await Chat.create([{ retailer: retailer._id, sales_man: salesMan._id }], { session }); const message = await Message.create([{ message: content, sender: retailer._id, receiver: salesMan._id }], { session }); await Chat.updateOne({ _id: newChat[0]._id }, { $push: { messages: message[0]._id } }, { session }); } const users = await User.find({ profile:salesMan._id }); const usersIds = []; for (let i = 0; i < users.length; i++) { const notification = await Notification.create([{ content: 'new conversation with '+user.name, type: 'chat' }], { session }); await User.updateOne({ _id: users[i]._id }, { $push: { notifications: notification[0]._id } }, { session }); usersIds.push({ id: users[i]._id.toString(), data: notification }); } Socket.SocketConnectedList(usersIds); await session.commitTransaction(); session.endSession(); res.status(200).json({ message: 'message successfully' }); } catch (error) { await session.abortTransaction(); session.endSession(); return next(error); } });
Leave a Comment