GraphQL

Write an awesome doc for GraphQL. A very nice an practical one extracted from GraphQL official documentation.

View on GitHub

Subscription

How Subscription operation type works

Client specifies a set of fields to be delivered to the client, but instead of immediately returning a single answer, a channel is opened and a result is sent to the client every time a particular event happens on the server

[!IMPORTANT]

Each subscription operation can subscribe to only one top-level field of the Subscription type. Meaning the following subscription operation is not valid:

subscription IndexPageEvents {
  notificationCreated {
    id
  }
  postCreated {
    author
    comment
  }
}

@apollo/server

Subscription resolvers

[!TIP]

Here you can see how withFilter should NOT be used in AS:

Inside the withFilter you should not change the resolved value, just filter it. For changing it use resolve function

NestJS + Apollo server

  1. Enable subscription in AS.
    • We need a 3rd-party lib for it called graphql-ws.
  2. ```diff GraphQLModule.forRoot({ driver: ApolloDriver, autoSchemaFile: join(__dirname, 'src', 'schema.gql'), sortSchema: true,
    • subscriptions: {
    • ‘graphql-ws’: true,
    • }, }) ```

    [!CAUTION]

    You cannot use GqlOptionsFactory as your return type. It is a generic type and in our case we wanna use ApolloServer as our driver, but if you use it then you won’t be able to access properties such as subscriptions:

    You should not use GqlModuleOptions since it is a generic type

    And here is how you do should do it instead:

    Use ApolloDriverConfig exported from @nestjs/apollo

  3. Use @Subscription to annotate your handler.
  4. pnpm add graphql-subscriptions
    
    • Provides a simple publish/subscribe API.
    • We usually need to back it with an external store such as Redis, or RabbitMQ, or anything other database (See a more complete list here).
      • pnpm add graphql-redis-subscriptions @nestjs/config ioredis class-transformer class-validator
        
      • For docker I am using this compose file.
      • cd libs/shared && nest g module pubsub
        
  5. To publish an event, we use the pubsub.publish method.
    • Often used within a mutation to trigger a client-side update when a part of the object graph has changed.
    • BTW it is also possible to use Javascript function generators instead. Like what we did for greet subscription.
  6. If you need to pass arguments to your field you need to utilize @ResolveField.
    • And if you need to access to the response you can use @Parent.