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

Redux Toolkit: How to normalize group chat messages?

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

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: {},
   },
};

如何使用 createEntityAdapternormalizr 库来实现?

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

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,然后使用来自 [=] 的消息数据丰富该 ID 列表的教科书示例12=].