GraphQL Subscriptions with OneGraph
Subscriptions are a feature in GraphQL that allow you to get data pushed to you in response to some event. Like GraphQL queries or mutations, you specify the data you need.
You can use OneGraph subscriptions to build services that react to events in the world outside of your application.
This port of Chrome's dino run game is built on a OneGraph subscription to npm packages (click to jump):
Let's see an example query:
subscription NpmSubscription {
npm {
allPublishActivity {
package {
name
time {
modified
}
distTags {
latest {
versionString
}
}
}
}
}
}
In this example, OneGraph will send us a new payload every time a package is published on NPM.
{
"data": {
"npm": {
"allPublishActivity": {
"package": {
"name": "unbounded",
"time": {
"modified": "2020-05-21T17:46:39.202Z"
},
"distTags": {
"latest": {
"versionString": "3.2.0"
}
}
}
}
}
},
"extensions": {
"eventId": "9803c9aa-14f9-434a-934e-fe233d51e628",
"subscriptionId": "538b64c6-d0a1-4d77-831a-71f9a3b637dd"
}
}
The subscription payload will have two custom fields in the top-level extensions
key.
The subscriptionId
is a globally-unique id for the subscription. You can use it to cancel the subscription. Learn more about canceling subscriptions below.
The eventId
is a globally-unique id for the event the subscription. In rare cases, OneGraph may send the same payload twice. For example, if you are receiving subscription payloads over webhooks and the connection drops. You can use the eventId
to ensure that you only handle each payload once.
Receiving subscription payloads
OneGraph has two modes for subscriptions
- Webhook-based subscriptions, mainly used for server-side apps.
- WebSocket-based subscriptions, mainly used by client-side apps.
Extra requirements by service
Some services have extra requirements to set up or run subscriptions.