Zeus supports GraphQL over WebSocket subscriptions out-of-the-box and is compatible with many popular GraphQL servers.
Two implementations are supported:
To use graphql-ws as your subscription transport you'll need to do the following:
# Generate the client
zeus schema.gql ./ --subscriptions graphql-ws
# Add graphql-ws to your project's dependencies
npm install graphql-ws
If you want to use the legacy method, use the --subscriptions legacy
flag instead. You may need to install ws depending on your setup.
No matter what implementation you chose, the usage remains the same:
// Create a new Subscription with some authentication headers
const wsChain = Subscription('wss://localhost:4000/graphql', {
get headers() {
return { Authorization: `Bearer ${getToken()}` };
},
});
// Subscribe to new messages
wsChain('subscription')({
message: {
body: true,
},
}).on(({ message }) => {
console.log(message.body);
});
If you need to unsubscribe from a subscription (e.g. you are developing a Single Page App), you can do it as follows:
// Subscribe to new messages
const onMessage = wsChain('subscription')({
message: {
body: true,
},
});
onMessage.on(({ message }) => {
console.log(message.body);
});
// Close the underlying connection
onMessage.ws.close();
While you can use wsChain('query')
or wsChain('mutation')
, Apollo strongly discourages this practice.