Websockets create a sustained connection between a client and a server
Messages can be sent on this connection in either direction.
It is a transport protocol.
GraphQL is a query language.
The GraphQL spec does not dictate a transport protocol. This means you can send GraphQL queries via HTTP, WebSocket or pidgeon mail if you really want to.
Notee: In urql, we even have a plugin to execute queries without any transport at all (using a schema on the client side).
Subscriptions are a mechanism in GraphQL spec indended for sending data using a sustained connection.
Just like how we send GraphQL (query language) request's over HTTP/S (transport protocol), with subscriptions, we can send GraphQL (query language) subscriptions over WebSocket (transport protocol).
DISCLAIMER: IF YOU HAVEN'T READ THE ABOVE, NOW IS YOUR LAST CHANCE
Okay so transport protocol aside, there are three different messages from graphql-ws we care about.
This is the first message we get from the client.
We persist the contents of this message as it contains headers which could be used later.
This is a message requesting the start of a subscription (with query, variables, and sub id)
We persist the contents of this message so we can keep track of subscribers and pass the arguments to resolvers later in the case of an event
See here for subscribe handler
This is a message requesting the termination of a subscription (with sub id)
We remove the subscription from our persistence layer if this is called.
When a socket is closed, subscriptions are no longer active.
We remove all persisted data from that socket (connection) in the case of a socket close.
See here for disconnect handler
When the lambda is called with a new_order event, we go to the persistence layer to find all subscribers of that event.
Following this, we execute their subscription with the new event before sending the result to those subscribed clients.