chat.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 === 'ADD_CHAT') {
  3. return {
  4. ...state,
  5. [chat_id]: {
  6. title,
  7. createdAt,
  8. lastModified,
  9. avatar,
  10. messages,
  11. members
  12. }
  13. }
  14. }
  15. if (type === "EDIT_CHAT") {
  16. return {
  17. ...state,
  18. [chat_id]: {
  19. title: title || state[chat_id].title,
  20. createdAt: state[chat_id].createdAt,
  21. lastModified: state[chat_id].lastModified,
  22. avatar: avatar || state[chat_id].avatar,
  23. messages: state[chat_id].messages,
  24. members: members || state[chat_id].members
  25. }
  26. }
  27. }
  28. if (type === "ADD_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. }
  43. if (type === "EDIT_MESSAGE") {
  44. let order;
  45. for (let key in state[chat_id].messages) {
  46. if (state[chat_id].messages[key]._id === messages[0]._id) {
  47. order = key
  48. }
  49. }
  50. return {
  51. ...state,
  52. [chat_id]: {
  53. title: state[chat_id].title,
  54. createdAt: state[chat_id].createdAt,
  55. lastModified,
  56. avatar: state[chat_id].avatar,
  57. messages: [
  58. ...state[chat_id].messages,
  59. state[chat_id].messages[order].text = msg_text,
  60. state[chat_id].messages[order].modified = true
  61. ],
  62. members: state[chat_id].members
  63. }
  64. }
  65. }
  66. return state
  67. }
  68. export default chatReducer