首页 > 解决方案 > GraphQL 订阅特定房间的(按 roomId)设置更改

问题描述

我想使用 gql 订阅来观察游戏室的设置变化。我有具有唯一房间代码的房间列表。每个房间都有设置属性。

例子:

class Room {
  roomCode: string;
  settings: {
    difficulty
    otherSetting
  }
}

现在我想订阅房间的设置更改(NestJS 示例):

@Subscription((type) => RoomSetting)
async roomSettingsChanged(@Args("roomCode") roomCode: RoomCode) {
  return this.pubSub.asyncIterator("roomSettingsChanged");
}

@Mutation((type) => RoomSetting)
async changeRoomSettings(
  @Args("roomCode") roomCode: RoomCode,
  @Args("RoomSettingsData") roomSettingsData: RoomSettingsData
): Promise<RoomSetting> {
  const newRoomSettings = await this.roomsSerive.changeRoomSettings(
    roomCode,
    roomSettingsData
  );
  this.pubSub.publish("roomSettingsChanged", {
    roomSettingsChanged: newRoomSettings,
  });
  return newRoomSettings;
}

RoomSettings 的外观如下:

RoomSettings {
  difficulty: "hard",
  otherSetting: "blabla"
}

现在,我如何在订阅中使用我传入订阅参数的 RoomCode 识别某些房间设置属于房间?我可以在 pubSub.publish 的一些额外变量中传递 roomCode 吗?或者,也许在 pubSub 中,我应该通过设置传递整个 Room 对象(那么如何在订阅解析器中仅获取设置)?RoomSettings 没有任何标识值(只是属于具有唯一 roomCode 的 Room)。我想实现这种情况:

  1. Someone subscribe to "roomSettingsChanged" and pass roomCode as argument
  2. When someone change room settings then the client, who subscribed to that room's settings change get notified with updates values.

标签: graphqlnestjspublish-subscribegraphql-subscriptions

解决方案


I probably found solution that seems to work as expected. Attach roomCode in subscription trigger string, eg:

this.pubSub.asyncIterator("roomSettingsChanged" + roomCode);

推荐阅读