chat.js 2.9 KB

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