12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- 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 }) {
- if (type === 'CHAT') {
- if (Object.keys(state).filter(id => id === chat_id).length === 0) { //новый чат
- return {
- ...state,
- [chat_id]: {
- title,
- createdAt,
- lastModified,
- avatar,
- messages,
- members
- }
- }
- }
- if (Object.keys(state).filter(id => id === chat_id).length === 1) { //измененный чат
- return {
- ...state,
- [chat_id]: {
- ...state[chat_id],
- title: title,
- avatar: avatar || state[chat_id].avatar,
- members: members
- }
- }
- }
- }
- if (type === "MESSAGE") {
- if ((state[chat_id]?.messages?.filter(msg => msg._id === msg_id).length === 0)) { //новое сообщение
- return {
- ...state,
- [chat_id]: {
- title: state[chat_id].title,
- createdAt: state[chat_id].createdAt,
- lastModified: state[chat_id].lastModified > msg_createdAt ? state[chat_id].lastModified : msg_createdAt,
- avatar: state[chat_id].avatar,
- 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],
- members: state[chat_id].members
- }
- }
- }
- if ((state[chat_id]?.messages?.filter(msg => msg._id === msg_id).length === 1)) { //измененное сообщение
- let order;
- for (let key in state[chat_id].messages) {
- if (state[chat_id].messages[key]._id === msg_id) {
- order = key
- }
- }
- let newMessages = [...state[chat_id].messages]
- newMessages[order].text = msg_text
- return {
- ...state,
- [chat_id]: {
- title: state[chat_id].title,
- createdAt: state[chat_id].createdAt,
- lastModified: state[chat_id].lastModified,
- avatar: state[chat_id].avatar,
- messages: newMessages,
- members: state[chat_id].members
- }
- }
- }
- }
- return state
- }
- export default chatReducer
|