在群聊中发送以前的消息

send previous messages in group chat

我在聊天应用程序中工作。我想将消息存储在这样的对象中:

{
  'room1': ['msg1', 'msg2', ...]
  'room2': ['msg3', 'msg4', ...]
  ...
}

我在 socket.io 服务器 roomMessages 中定义了一个变量 问题是当我想使用 roomMessages[room].push(data); 在特定房间中添加一条消息时,它显示了这个错误:TypeError: Cannot read properties of undefined (reading 'push') 这是我的 socket.io 代码:

const roomMessages = {};

roomsNamespace.use((socket, next) => {
  const token = socket.handshake.query.token;
  console.log(token);
  if (!token) return next(new Error("not auth"));
  next();
});

roomsNamespace.on("connection", (socket) => {
  const token = socket.handshake.query.token;
  const apiService = new ApiService(process.env.BE_URL, token);
  const room = socket.handshake.query.room;
  socket.on("join-room", async () => {
    socket.join(room);
    await apiService.joinRoom(room);
    const usersInThisRoom = await apiService.getUsersInRoom(room);
    roomsNamespace.in(room).emit("all-users", usersInThisRoom);
    socket.emit("room-messages", roomMessages[room]);
  });
  socket.on("chat-message", (data) => {
    // console.log(data);
    if (roomMessages[room]) roomMessages[room].push(data);
    roomsNamespace.in(room).emit("chat-message", data);
  });

基本上,我想在用户加入聊天时发送之前的消息 如何修复此错误?

你可以这样做

const roomMessages = {};

const getMessages = (room) => roomMessages[room] || []
const addMessage = (room, message) => {
  roomMessages[room] = [...getMessages(room), message]
}



roomsNamespace.use((socket, next) => {
  const token = socket.handshake.query.token;
  console.log(token);
  if (!token) return next(new Error("not auth"));
  next();
});

roomsNamespace.on("connection", (socket) => {
  const token = socket.handshake.query.token;
  const apiService = new ApiService(process.env.BE_URL, token);
  const room = socket.handshake.query.room;
  socket.on("join-room", async () => {
    socket.join(room);
    await apiService.joinRoom(room);
    const usersInThisRoom = await apiService.getUsersInRoom(room);
    roomsNamespace.in(room).emit("all-users", usersInThisRoom);
    socket.emit("room-messages", getMessages(room));
  });
  socket.on("chat-message", (data) => {
    // console.log(data);
    addMessage(room, data)
    roomsNamespace.in(room).emit("chat-message", data);
  });


通过这种方式,如果您稍后需要,您可以更改 messageRepository 将数据存储在 redis 中或任何您想要的地方的实现