messages.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const MessageModel = require('../model/message');
  2. const UserModel = require('../model/user');
  3. const ChatModel = require('../model/chat');
  4. const listMessages = async (req, res, next) => {
  5. try {
  6. const userId = req.user.id;
  7. const messages = await MessageModel.getList(userId, req.query);
  8. return res.json({
  9. status: 'success',
  10. code: 200,
  11. data: {
  12. ...messages,
  13. },
  14. });
  15. } catch (e) {
  16. next(e);
  17. }
  18. };
  19. const listMessagesById = async (req, res, next) => {
  20. try {
  21. const userId = req.user.id;
  22. const companionId = req.params.companionId;
  23. const messages = await MessageModel.getListById(companionId, userId);
  24. return res.json({
  25. status: 'success',
  26. code: 200,
  27. data: [...messages],
  28. });
  29. } catch (e) {
  30. next(e);
  31. }
  32. };
  33. const sentMessage = async (req, res, next) => {
  34. try {
  35. const { id, message } = req.body;
  36. const user = req.user;
  37. const userId = user.id;
  38. const companion = await UserModel.findById(id);
  39. const isChat = await ChatModel.getByField(id, userId);
  40. const isCompanionChat = await ChatModel.getByField(userId, id);
  41. const { name, lastName, avatarUrl, color, number } = user;
  42. if (companion && isChat && isCompanionChat) {
  43. const newMessage = await MessageModel.add({
  44. message,
  45. name,
  46. lastName,
  47. avatarUrl,
  48. color,
  49. number,
  50. companionId: id,
  51. owner: userId,
  52. });
  53. await MessageModel.add({
  54. message,
  55. name,
  56. lastName,
  57. avatarUrl,
  58. color,
  59. number,
  60. companionId: userId,
  61. owner: id,
  62. });
  63. const { total } = await MessageModel.getList(userId, {});
  64. await ChatModel.update(isChat._id, { total });
  65. const { total: Total } = await MessageModel.getList(id, {});
  66. await ChatModel.update(isCompanionChat._id, { total: Total });
  67. return res.status(201).json({
  68. status: 'success',
  69. code: 201,
  70. data: newMessage,
  71. });
  72. }
  73. } catch (e) {
  74. next(e);
  75. }
  76. };
  77. module.exports = {
  78. listMessages,
  79. sentMessage,
  80. listMessagesById,
  81. };