chat.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. function chatReducer(state = {}, { type, chat_id, title, createdAt, lastModified, avatar, members, messages, msg_id, msg_text, msg_createdAt, msg_owner, msg_media, msg_replies }) {
  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: msg_createdAt,
  36. avatar: state[chat_id].avatar,
  37. messages: [...state[chat_id].messages, { _id: msg_id, text: msg_text, createdAt: msg_createdAt, owner: msg_owner, media: msg_media, replies: msg_replies }],
  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. newMessages[order].modified = true
  52. return {
  53. ...state,
  54. [chat_id]: {
  55. title: state[chat_id].title,
  56. createdAt: state[chat_id].createdAt,
  57. lastModified: state[chat_id.createdAt],
  58. avatar: state[chat_id].avatar,
  59. messages: newMessages,
  60. members: state[chat_id].members
  61. }
  62. }
  63. }
  64. }
  65. return state
  66. }
  67. export default chatReducer