messages.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 isUser = await ChatModel.getByField(id, userId);
  40. const isCompanion = await ChatModel.getByField(userId, id);
  41. const { name, lastName, avatarUrl, color, number } = user;
  42. if (companion && isUser && isCompanion) {
  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. return res.status(201).json({
  64. status: 'success',
  65. code: 201,
  66. data: newMessage,
  67. });
  68. }
  69. } catch (e) {
  70. next(e);
  71. }
  72. };
  73. module.exports = {
  74. listMessages,
  75. sentMessage,
  76. listMessagesById,
  77. };