GraphQL subscribe to specific room's (by roomId) settings change

495 views Asked by At

I would like to use gql subscription to watch for game room's settings change. I have list of Rooms with unique roomCode. Every Room has settings properties.

Example:

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

And now I would like to subscribe for room's settings change (NestJS example):

@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;
}

Where the RoomSettings looks like:

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

And now how can I in subscription identify that some roomSettings belong to room with RoomCode I pass in subscription args? Can I pass roomCode in some extra variables in pubSub.publish? Or maybe in pubSub I sould pass whole Room object with settings (how to get only settings in subscription resolver then)? RoomSettings does not have any identify value (just belongs to Room, which has unique roomCode). I would like to achieve this scenario:

  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.
1

There are 1 answers

0
vicodin On BEST ANSWER

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

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