chat.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. function chatReducer(state = {}, { type, chat_id, title, createdAt, lastModified, avatar, members, messages, msg_id, msg_text, msg_createdAt, msg_owner, msg_media, msg_replyTo, socket = false }) {
  2. if (type === 'CHAT') {
  3. if (Object.keys(state).filter(id => id === chat_id).length === 0) { //новый чат
  4. return {
  5. ...state,
  6. [chat_id]: {
  7. title,
  8. createdAt,
  9. lastModified,
  10. avatar,
  11. messages,
  12. members
  13. }
  14. }
  15. }
  16. if (Object.keys(state).filter(id => id === chat_id).length === 1) { //измененный чат
  17. return {
  18. ...state,
  19. [chat_id]: {
  20. ...state[chat_id],
  21. title: title,
  22. avatar: avatar,
  23. members: members
  24. }
  25. }
  26. }
  27. }
  28. if (type === "MESSAGE") {
  29. if ((state[chat_id]?.messages?.filter(msg => msg._id === msg_id).length === 0)) { //новое сообщение
  30. return {
  31. ...state,
  32. [chat_id]: {
  33. title: state[chat_id].title,
  34. createdAt: state[chat_id].createdAt,
  35. lastModified: state[chat_id].lastModified > msg_createdAt ? state[chat_id].lastModified : msg_createdAt,
  36. avatar: state[chat_id].avatar,
  37. messages: socket ? [...state[chat_id].messages, { _id: msg_id, text: msg_text, createdAt: msg_createdAt, owner: msg_owner, media: msg_media, replyTo: msg_replyTo }] : [{ _id: msg_id, text: msg_text, createdAt: msg_createdAt, owner: msg_owner, media: msg_media, replyTo: msg_replyTo }, ...state[chat_id].messages],
  38. members: state[chat_id].members
  39. }
  40. }
  41. }
  42. if ((state[chat_id]?.messages?.filter(msg => msg._id === msg_id).length === 1)) { //измененное сообщение
  43. let order;
  44. for (let key in state[chat_id].messages) {
  45. if (state[chat_id].messages[key]._id === msg_id) {
  46. order = key
  47. }
  48. }
  49. let newMessages = [...state[chat_id].messages]
  50. newMessages[order].text = msg_text
  51. return {
  52. ...state,
  53. [chat_id]: {
  54. title: state[chat_id].title,
  55. createdAt: state[chat_id].createdAt,
  56. lastModified: state[chat_id].lastModified,
  57. avatar: state[chat_id].avatar,
  58. messages: newMessages,
  59. members: state[chat_id].members
  60. }
  61. }
  62. }
  63. }
  64. return state
  65. }
  66. export default chatReducer