1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- function chatReducer(state = {}, { type, chat_id, title, createdAt, lastModified, avatar, members, messages, msg_id, msg_text, msg_createdAt, msg_owner, msg_media, msg_replies }) {
- 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,
- 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: msg_createdAt,
- avatar: state[chat_id].avatar,
- messages: [...state[chat_id].messages, { _id: msg_id, text: msg_text, createdAt: msg_createdAt, owner: msg_owner, media: msg_media, replies: msg_replies }],
- 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
- newMessages[order].modified = true
- return {
- ...state,
- [chat_id]: {
- title: state[chat_id].title,
- createdAt: state[chat_id].createdAt,
- lastModified: state[chat_id.createdAt],
- avatar: state[chat_id].avatar,
- messages: newMessages,
- members: state[chat_id].members
- }
- }
- }
- }
- return state
- }
- export default chatReducer
|