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.

Check out this runnable code sandbox.

Here is another 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'
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