Rooms/Channels and userId in Meteor.js

Rooms/Channels and userId in Meteor.js

本文关键字:in Meteor js userId and Channels Rooms      更新时间:2023-09-26

我正在使用meteor.js构建一个多人回合制游戏。该应用程序将处理多个游戏,所以我想把我的用户分成房间。在使用socket之前,我已经这样做了。io通道,但我正在努力理解它应该如何在流星。

我想达到的流程是:

  1. 用户访问http://localhost:3000/join/userId

  2. 我做一个服务器端调用一个外部API使用"sessionId"作为参数,获取用户的userId,他分配的roomId和允许的userId的数组为这个房间

  3. 我想为用户创建一个具有roomId的房间或将他加入到现有的房间。我知道我应该创建一个"房间"集合,但我不知道如何将用户绑定到我的房间,并仅向给定房间中的用户发布消息。

我想避免使用'accounts'包,因为我不需要我这边的授权——它将由上面提到的第2步处理——但是如果最简单和最干净的方法包括添加这个包,我可以改变主意。

您的Rooms集合可能看起来像:

{
    _id: "<auto-generated>",
    roomId: "roomId",
    users: [ "user1", "user2", "user3", ... ],
    messages: [
        { message: "", userId: "" },
        { message: "", userId: "" },
        { message: "", userId: "" },
        ...
    ]
}
服务器端API调用返回

userIdroomId等信息

所以你可以输入

Rooms.update({ roomId: roomId }, { $push: { users: userId } }, { upsert: true });

这将把用户推到现有的房间或创建一个新房间并添加用户。

你的发布函数可以像这样:

Meteor.publish("room", function(roomId) {
    // Since you are not using accounts package, you will have to get the userId using the sessionId that you've specified or some other way.
    // Let us assume your function getUserId does just that.
    userId: getUserId( sessionId );
    return Rooms.find({ roomId: roomId, users: userId });
    // Only the room's users will get the data now.
});