Redux Toolkit:如何规范群聊消息?



我有一个从服务器返回的消息数组,其中每个聊天消息具有以下格式:

export interface ChatMessage {
_id: string | number;
text: string;
createdAt: Date | number;
user: ChatUser;
groupId: number;
}
interface ChatUser {
_id: string | number;
name: string;
}

我想通过groupId规范化消息列表,然后通过嵌套在里面的消息Id来实现这样的事情:
const messages = {
ids: ['group1', 'group2'],
entities: {
group1: {
ids: ['msg1', 'msg2'],
msg1: {},
msg2: {},
},
group2: {
ids: ['msg3', 'msg4'],
msg3: {},
msg4: {},
},
};

我如何用createEntityAdapter或normalizr库实现这一点?

我认为如果状态设计得好,选择器可以完成繁重的工作。我会尝试这样做:

const initialState = {
messages: {}, // messages by id
// map groupIds to an object with messageIds and their createdAt timestamp
groups: {
/* Example:
groupId1: { messageId1: '2022-05-23', messageId2: '2022-05-22'}
*/
},
users: {}, // users by id
};
chatMessagesFromServer.forEach(message => {
const { user } = message;
// Save message by id, but only with a reference to the userId
const normalizedMessage = { ...message, userId: user._id };
delete normalizedMessage.user;
state.messages[message._id] = normalizedMessage;
// Associate groups with messages
if (state.groups[message.groupId]) {
state.groups[message.groupId][message.id] = message.createdAt;
} else {
state.groups[message.groupId] = { [message.id]: message.createdAt };
}
// Save user by id
state.users[user._id] = user;
});

按时间顺序检索一个组中的所有消息,例如,一个记忆选择器访问state.groups以获取消息id,然后用state.messages的消息数据丰富该id列表的教科书示例。

相关内容

  • 没有找到相关文章