I want to use the library https://github.com/apollographql/graphql-tag I'm looking for someone smarter than me that understands how to actually use it.
Say I have a GraphQL query document like so:
const query = gql`
{
user(id: 5) {
...User_user
}
}
${userFragment}
`
How do I get now the string to add in the http body request? I end up with an object, which allows me to do some introspection and manipulations, great, but how to get the actual body string for the server request?
I'm missing something obvious I guess...
The object you get by applying
qql
to your graphql query code is the AST (abstract syntax tree) for the graphql. This AST is normally used with the apollo-client to execute requests. However, you can use any other library that is capable of executing GraphQL requests using AST.Assuming you are willing to use Apollo, here's an example on their website how it works (https://www.apollographql.com/docs/react/data/queries).
This example is for React with hooks (this is a primary way to use Apollo). If you still want to use Apollo but don't use React then you could use bare ApolloClient and still use your AST to run queries. See the link below to learn how to use ApolloClient directly.
https://www.apollographql.com/docs/react/api/core/ApolloClient/
Finally, if you are not willing to bother with Apollo and/or AST, you can simply execute the query directly. In this case, you don't need to use
gql
and parse it into AST. See a simplified but working example below.Note: The implementation above (especially the query part) depends on your GraphQL schema and backend implementation. It may differ, but in principle, this should work with most modern graphql backends.