Search code examples
websocketgraphqlgraphql-jsgraphql-subscriptions

Raw javascript GraphQL subscription with WebSocket not working


I am trying to create a raw piece of code that listen to a graphQL Subscription but I am not able to make it work for some reasons.

I am trying to mimic the raw request sent from the GraphQL console which you can see here

Request example

it seems pretty simple. So I made the following javascript code:

const WebSocket = require("ws");

const connection = new WebSocket("ws://localhost:4000/graphql")

connection.onopen = () => {
  console.log("connection open")
  let init = JSON.stringify({type:"connection_init",payload:{Authorization:"Bearer eyJhbG.....HIDDEN....dDgw"}})
  let listen = JSON.stringify({"id":"1","type":"start","payload":{"variables":{},"extensions":{},"operationName":null,"query":"subscription {\n  followJob(idJob: \"ck0pa2r8r8pit0b17f3k6s729\") {\n    progress\n  }\n}\n"}})
  connection.send(init)
  connection.send(listen)
}

connection.onmessage = e => {
  console.log("data coming")
  console.log(e.data)
}

connection.onerror = e =>{
  console.log(e)
}


(function wait () {
  setTimeout(wait, 1000000);
})();

The GraphQL Server does receive the request and has the exact same message data than the request made from the console but for some reasons it doesn't process the query after that, doesn't throw any error or message in logs...

Do you have any idea about what I might be missing?

Thank you very much for your help.


Solution

  • Just had to specify websocket protocol like so

    const connection = new WebSocket("ws://localhost:4000/graphql","graphql-ws")