Subscriptions

The Chargetrip API relies on GraphQL technology, so some requests use a subscription mechanism. Unlike queries or mutations, subscriptions are long-lasting operations and can change their result over time. These operations are handled by a websocket. Authenticating and communicating with this websocket is different than a regular query or mutation.

Note

Websocket connections can't be used out of the box in a terminal. The steps below use a library called wscat. It's open source and can be downloaded here.

Step 1

Initialize the websocket

To get started with the websocket, initialize a connection. It is important to set the correct WebSocket protocol. We support the graphql-ws and the graphql-transport-ws as Sec-WebSocket-Protocol. The latter is preferred, as described over here. Each of these protocols uses a different base url.

Step 2

Authorization on the websocket

Once a connection has been opened, authorization needs to be set up. This can be done by sending a message with the correct type and payload. The type will need to be init and the payload must contain an x-client-id and an x-app-id. If everything was successful, the websocket returns; { "type": "connection_ack" }.

Step 3

Communicating on the websocket

After authorization, start sending subscriptions and receiving data. To send a subscription, add an id to any unique identifier in the message. The id will be returned to ensure that the right message was received.

To illustrate how this works, the routeUpdatedById subscription with the status field is being sent.

Once everything is properly set-up and a routeId was correctly set in the variables and query, the WebSocket will respond with an object that contains the status. For more information about the route subscription and responses have a look at the route section. If a routeId is not set in the variables, there will be no response from the server.

Depending on websocket protocol the message type needs to be either start or subscription.

Step 4

Closing the connection

After getting the desired results, the connection can be closed by pressing ctrl + c or cmd + c in a terminal.