123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- 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,
- 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
|