chats.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. const updatedUser = await ChatModel.getByField(id, userId);
  42. return res.status(200).json({
  43. status: 'success',
  44. code: 200,
  45. data: updatedUser,
  46. });
  47. }
  48. if (companion && !isUser && !isCompanion) {
  49. const updatedUser = await ChatModel.add({
  50. name,
  51. lastName,
  52. avatarUrl,
  53. color,
  54. companionId: id,
  55. owner: userId,
  56. });
  57. await ChatModel.add({
  58. name: Name,
  59. lastName: LastName,
  60. avatarUrl: AvatarUrl,
  61. color: Color,
  62. companionId: userId,
  63. owner: id,
  64. });
  65. return res.status(201).json({
  66. status: 'success',
  67. code: 201,
  68. data: updatedUser,
  69. });
  70. }
  71. } catch (e) {
  72. next(e);
  73. }
  74. };
  75. module.exports = {
  76. listChats,
  77. startChat,
  78. };