API

subscriptionType


subscriptionType

1subscriptionType(typeName:string, fn: SubscriptionTypeConfig): NexusSubscriptionType

Create a GraphQL Subscription type.

A subscription type configuration field is like an object type with the following differences:

  1. It has a subscribe field. You should return an async iterator here. This is called once for each subscription a client sends.
  2. The root param of the resolve field is called for each promise returned by the async iterator setup. The resolver is responsible for transforming the shape of data returned by your subscription stream into types that conform to your GraphQL schema.

Here is a runnable example using Apollo Server and Apollo PubSub with Express.

1import { ApolloServer, PubSub } from 'apollo-server-express'
2import express from 'express'
3import * as HTTP from 'http'
4import * as path from 'path'
5import {
6 arg,
7 inputObjectType,
8 makeSchema,
9 mutationType,
10 objectType,
11 subscriptionType,
12} from '@nexus/schema'
13
14const pubsub = new PubSub()
15
16const schema = makeSchema({
17 shouldExitAfterGenerateArtifacts:
18 process.env.NEXUS_SHOULD_EXIT_AFTER_GENERATE_ARTIFACTS === 'true',
19 outputs: {
20 typegen: path.join(__dirname, 'node_modules/@types/nexus-typegen/index.d.ts'),
21 schema: path.join(__dirname, './api.graphql'),
22 },
23 types: [
24 mutationType({
25 definition(t) {
26 t.field('createOneUser', {
27 type: 'User',
28 args: {
29 data: arg({
30 type: nonNull(
31 inputObjectType({
32 name: 'CreateOneUserInput',
33 definition(t) {
34 t.nonNull.string('email')
35 },
36 })
37 ),
38 }),
39 },
40 async resolve(_, args) {
41 const data = args.data
42 await pubsub.publish('user_added', { data })
43 return data
44 },
45 })
46 },
47 }),
48 subscriptionType({
49 definition(t) {
50 t.field('createOneUser', {
51 type: 'User',
52 subscribe() {
53 return pubsub.asyncIterator('user_added')
54 },
55 async resolve(userPromise) {
56 const user = await userPromise.data
57 return user
58 },
59 })
60 },
61 }),
62 objectType({
63 name: 'User',
64 definition(t) {
65 t.string('email')
66 },
67 }),
68 ],
69})
70
71const apollo = new ApolloServer({ schema })
72const app = express()
73const http = HTTP.createServer(app)
74
75apollo.applyMiddleware({ app })
76apollo.installSubscriptionHandlers(http)
77
78http.listen(4000, () => {
79 console.log(`🚀 GraphQL service ready at http://localhost:4000/graphql`)
80})

Here is a runnable example with a minimalistic schema.

1import { ApolloServer } from 'apollo-server-express'
2import express from 'express'
3import * as HTTP from 'http'
4import * as path from 'path'
5import { makeSchema, subscriptionType } from '@nexus/schema'
6
7const schema = makeSchema({
8 shouldExitAfterGenerateArtifacts:
9 process.env.NEXUS_SHOULD_EXIT_AFTER_GENERATE_ARTIFACTS === 'true',
10 outputs: {
11 typegen: path.join(__dirname, 'node_modules/@types/nexus-typegen/index.d.ts'),
12 schema: path.join(__dirname, './api.graphql'),
13 },
14 types: [
15 subscriptionType({
16 definition(t) {
17 t.boolean('truths', {
18 subscribe() {
19 return (async function*() {
20 while (true) {
21 await new Promise(res => setTimeout(res, 1000))
22 yield Math.random() > 0.5
23 }
24 })()
25 },
26 resolve(eventData) {
27 return eventData
28 },
29 })
30 },
31 }),
32 ],
33})
34
35const apollo = new ApolloServer({ schema })
36const app = express()
37const http = HTTP.createServer(app)
38
39apollo.applyMiddleware({ app })
40apollo.installSubscriptionHandlers(http)
41
42http.listen(4000, () => {
43 console.log(`🚀 GraphQL service ready at http://localhost:4000/graphql`)
44})
Edit this page on Github