Skip to content
This repository was archived by the owner on Sep 27, 2023. It is now read-only.
This repository was archived by the owner on Sep 27, 2023. It is now read-only.

Distinguish union type via __typename in subscription updater function #186

@n1ru4l

Description

@n1ru4l

Schema:

type User {
  id: ID!
  name: String!
}

type UserAddUpdate {
  user: User!
}

type UserRemoveUpdate {
  userId: ID!
}

union UserUpdateSubscription = UserAddUpdate | UserRemoveUpdate

type Subscription {
  userUpdate: UserUpdateSubscription!
}

Subscription:

React.useEffect(() => {
    const subscription = requestSubscription<chatUserUpdateSubscription>(
      environment,
      {
        subscription: UserUpdateSubscription,
        variables: {},
        updater: (store) => {
          const users = ConnectionHandler.getConnection(
            store.getRoot(),
            "chat_users"
          );

          const updateRecord = store.getRootField("userUpdate");

          if (!users || !updateRecord) return;

          if (updateRecord.getValue("__typename") === "UserAddUpdate") {
            const edge = ConnectionHandler.createEdge(
              store,
              users,
              updateRecord.getLinkedRecord("user"),
              "User"
            );
            ConnectionHandler.insertEdgeAfter(users, edge);
          } else if (
            updateRecord.getValue("__typename") === "UserRemoveUpdate"
          ) {
            // updateRecord should be
            // RecordProxy<{
            //   readonly __typename: "UserRemoveUpdate";
            //   readonly userId: string;
            // }
            // userId should be a string
            const userId = updateRecord.getValue("userId");
            if (typeof userId !== "string") return;
            ConnectionHandler.deleteNode(users, userId);
          }
        },
      }
    );
    return () => subscription.dispose();
  }, [environment]);

Maybe it is possible to correctly infer the type based on the __typename property comparison?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions