Subscriptions allow clients to listen to real-time messages from the server. In GraphQL, it’s straightforward to enable subscriptions on any type.
@withSubscription
directive to the schema as part of the type
definition, as in the following example:
@withSubscription
with @auth
@withSubscription
.
Consider following Schema that has both the @withSubscription
and @auth
directives defined on type Todo
.
X-Dgraph-AuthToken
header
and uses the USER
claim to apply a Role-based Access Control (RBAC). The
authorization rule enforces that only to-do tasks owned by $USER
are returned.
subscription-transport-ws
.
Clients must be instantiated using the WebSocket URL of the GraphQL API which is
your
Dgraph GraphQL endpoint
with https
replaced by wss
.
If your Dgraph endpoint is https://<path>
the WebSocket URL is wss://<path>
If your GraphQL API is configured to expect a JWT token in a header, you must
configure the WebSocket client to pass the token. Additionally, the subscription
terminates when the JWT expires.
Here are some examples of frontend clients setup.
subscriptions-transport-ws
modules.
In order to use a GraphQL subscription query in a component, you need to
subscriptionClient
subscriptionExchange
using the
ubscriptionClient
process.env.REACT_APP_DGRAPH_ENDPOINT
is your
Dgraph GraphQL endpointprocess.env.REACT_APP_DGRAPH_WSS
is the WebSocket URLprops.token
is the JWT token of the logged-in user.fetchOptions
and
in the WebSocket client using connectionParams
.
Assuming we use graphql-codegen, we can define a subscription query:
messages.data.queryTodo
to
display the updated list of to dos.
connectionParams
, as
follows.
Dgraph.Authorization
configuration of your
GraphQL schema.
@withSubscription
directive to custom DQL queries by
specifying @withSubscription
on individual DQL queries in type Query
, and
those queries are added to type subscription
.
For example, see the custom DQL query queryUserTweetCounts
below:
queryUserTweetCounts
is added to the subscription
type, allowing users to
subscribe to this query.
permessage-deflate
compression if the GraphQL client’s
Sec-Websocket-Extensions
request header includes permessage-deflate
, as
follows: Sec-WebSocket-Extensions: permessage-deflate
.