Complete the code to start a WebSocket connection for GraphQL subscriptions.
const wsClient = new WebSocket('[1]');
The WebSocket URL must start with ws:// or wss:// for secure connections. Here, ws://localhost:4000/graphql is correct.
Complete the code to send a GraphQL subscription start message over WebSocket.
wsClient.send(JSON.stringify({ type: '[1]', id: '1', payload: { query: SUBSCRIPTION_QUERY } }));The message type to start a subscription is start. This tells the server to begin sending subscription data.
Fix the error in the WebSocket message handler to correctly parse incoming data.
wsClient.onmessage = event => { const data = JSON.parse(event.[1]); console.log(data); };The WebSocket event object has a data property containing the message as a string. We parse event.data.
Fill both blanks to correctly handle a GraphQL subscription stop message and close the WebSocket.
if (message.type === '[1]') { wsClient.[2](); }
The message type to stop a subscription is stop. To close the WebSocket, call wsClient.close().
Fill all three blanks to initialize a WebSocket connection with connection_init message and send it.
const initMessage = { type: '[1]', payload: { headers: { Authorization: '[2]' } } }; wsClient.[3](JSON.stringify(initMessage));The connection initialization message type is connection_init. The Authorization header uses a bearer token string. To send the message, use wsClient.send().