UNPKG

1.86 kBMarkdownView Raw
1# graphql-subscriptions
2
3GraphQL subscriptions is a simple npm package that lets you wire up GraphQL with a pubsub system (like Redis) to implement subscriptions in GraphQL.
4
5### Installation
6
7`npm install graphql-subscriptions`
8
9
10### Example usage
11
12```js
13import { PubSub, SubscriptionManager } from 'graphql-subscriptions';
14import schema from './schema';
15
16// PubSub can be easily replaced, for example with https://github.com/davidyaha/graphql-redis-subscriptions
17const pubsub = new PubSub();
18
19const subscriptionManager = new SubscriptionManager({
20 schema,
21 pubsub,
22
23 // setupFunctions maps from subscription name to a map of channel names and their filter functions
24 // in this case it will subscribe to the commentAddedChannel and re-run the subscription query
25 // every time a new comment is posted whose repository name matches args.repoFullName.
26 setupFunctions: {
27 commentAdded: (options, args) => ({
28 newCommentsChannel: {
29 filter: comment => comment.repository_name === args.repoFullName,
30 },
31 }),
32 },
33});
34
35// start a subscription
36subscriptionManger.subscribe({
37 query: `
38 subscription newComments($repoName: String!){
39 commentAdded(repoName: $repoName) { # <-- this is the subscription name
40 id
41 content
42 createdBy {
43 username
44 }
45 }
46 }
47 `,
48 variables: {
49 repoName: 'apollostack/GitHunt-API',
50 },
51 context: {},
52 callback: (err, data) => console.log(data),
53});
54
55// publish to the channel
56pubsub.publish('newCommentsChannel', {
57 id: 123,
58 content: 'Test',
59 repoFullName: 'apollostack/GitHunt-API',
60 posted_by: 'helfer',
61});
62
63// the query will run, and the callback will print
64// {
65// data: {
66// commentAdded: {
67// id: 123,
68// content: 'Test',
69// createdBy: {
70// username: 'helfer',
71// }
72// }
73// }
74// }
75
76```
77
78
79