chats.js 1.9 KB

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