Skip to content

Subscription

r-kohale9 edited this page Dec 18, 2019 · 1 revision

Apollo graphql Subscriptions

Apollo Server

Subscriptions depend on use of a publish and subscribe primitive to generate the events that notify a subscription. PubSub is a factory that creates event generators that is provided by all supported packages.

Step 1-

Creating a schema for subscription in schema.graphql

type Subscription {
  exampleSubscription(input: ExampleSubscriptionInput): ReturnEntityInput
}

input ExampleSubscriptionInput {
  id: Int!
}

type ReturnEntityInput {
  id: Int
  content: String!
}

Step 2-

Now the functioning of the subscription needs to defined in the resolver.ts(/.js) under the Subscription keyword/object with the same name as the one defined in the schema.graphql.

Subscription: {
  exampleSubscription: {
    subscribe: withFilter(
      () => pubsub.asyncIterator(EXAMPLE_SUBSCRIPTION),
      (payload, variables) => {
        return payload.example.id === variables.id; // Some logic to separate the required data from the rest.
      }
    );
  }
}

Inside our resolver map, we add a Subscription resolver that returns an AsyncIterator, which listens to the events asynchronously. Sometimes a client will want to filter out specific events based on context and arguments. To do so, we can use the withFilter helper from the apollo-server or apollo-server-{integration} package i.e "graphql-subscriptions" to control each publication for each user. Inside of withFilter, the AsyncIterator created by PubSub is wrapped with a filter function.

Apollo Client (React)

Step 1

Define Subscription Queries in .grphaql file -> Subscription queries look just like any other kind of operation:

subscription onExamaple($input: ExampleSubscriptionInput) {
  exampleSubscription(input: $input) {
    ReturnEntityInput
  }
}

Step 2

With GraphQL subscriptions your client will be alerted on push from the server and you should choose the pattern that fits your application the most:

  • Use it as a notification and run any logic you want when it fires, for example alerting the user or refetching data
  • Use the data sent along with the notification and merge it directly into the store (existing queries are automatically notified) With subscribeToMore, you can easily do the latter.

subscribeToMore is a function available on every query result in React Apollo. It works just like fetchMore, except that the update function gets called every time the subscription returns, instead of only once.

Add a function called subscribeToNewExample that will subscribe using subscribeToMore and update the query's store with the new data using updateQuery.

const subscribeToNewExample = (subscribeToMore, id, history, navigation) =>
  subscribeToMore({
    document: LISTING_SUBSCRIPTION,
    variables: { id: id },
    updateQuery: (
      prev,
      {
        subscriptionData: {
          data: {
            exampleSubscription: { mutation }
          }
        }
      }
    ) => {
      // return logic
      }
      return prev;
    }
  });

and start the actual subscription by calling the subscribeToNewComments function with the subscription variables as: this.props.subscibeToNewExample();