chats.js 1.6 KB

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