I would like to use text/event-stream
via axios
library in nodejs to subscribe GQL subscriptions.
It is possible? And how can I do it?
I am trying to use my code:
console.log("a")
const axios = require('axios');
const response = await axios.get(
'http://localhost:4003/graphql',
{ headers: { responseType: 'stream', accept: "text/event-stream" } }
);
console.log("b")
But b
is never printed.
What is wrong?
You can check docs here:
https://the-guild.dev/graphql/yoga-server/docs/features/subscriptions
There are 2 problems.
Correct example:
curl -N -H "accept:text/event-stream" http://localhost:4000/graphql?query=subscription%20%7B%0A%20%20countdown%28from%3A%205%29%0A%7D
but in your code there is only /graphql
. So server event does not know what do you asking.
First option in curl is -N
. Reading man curl
you can find that it means no-buffer
.
-N, --no-buffer Disables the buffering of the output stream. In normal work situations, curl will use a standard buffered output stream that will have the effect that it will output the data in chunks, not necessarily exactly when the data arrives. Using this option will disable that buffering. Note that this is the negated option name documented. You can thus use --buffer to enforce the buffering. Example: curl --no-buffer https://example.com See also -#, --progress-bar.
Although this option works in curl
What is the LIBCURL equivalent to --N/--no-buffer?
it is not available in axios
.
In curl
you can send request and receive responses before closing connection. In axios you have to close connection to get response.
I recommend you use other methods described in first link. Read about Apollo Client, Urql and Relay and chose something. They are designed to help you, decrease amount of your code and simplify error handling.