chats.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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, online } = companion;
  27. const {
  28. name: Name,
  29. lastName: LastName,
  30. avatarUrl: AvatarUrl,
  31. color: Color,
  32. online: Online,
  33. } = user;
  34. if (companion && (isUser || isCompanion)) {
  35. await ChatModel.update(isUser._id, {
  36. name,
  37. lastName,
  38. avatarUrl,
  39. color,
  40. online,
  41. });
  42. await ChatModel.update(isCompanion._id, {
  43. name: Name,
  44. lastName: LastName,
  45. avatarUrl: AvatarUrl,
  46. color: Color,
  47. online: Online,
  48. });
  49. const updatedChat = await ChatModel.getByField(id, userId);
  50. return res.status(200).json({
  51. status: 'success',
  52. code: 200,
  53. data: updatedChat,
  54. });
  55. }
  56. if (companion && !isUser && !isCompanion) {
  57. const newChat = await ChatModel.add({
  58. name,
  59. lastName,
  60. avatarUrl,
  61. color,
  62. online,
  63. companionId: id,
  64. owner: userId,
  65. });
  66. await ChatModel.add({
  67. name: Name,
  68. lastName: LastName,
  69. avatarUrl: AvatarUrl,
  70. color: Color,
  71. online: Online,
  72. companionId: userId,
  73. owner: id,
  74. });
  75. return res.status(201).json({
  76. status: 'success',
  77. code: 201,
  78. data: newChat,
  79. });
  80. }
  81. } catch (e) {
  82. next(e);
  83. }
  84. };
  85. module.exports = {
  86. listChats,
  87. startChat,
  88. };