Hands-On Full-Stack Web Development with GraphQL and React
上QQ阅读APP看书,第一时间看更新

Sending GraphQL queries

We can test this query using any HTTP client, such as Postman, Insomnia, or any you are used to. This book covers HTTP clients in the next section of this chapter. If you want to send the following queries on your own, you can read the next section and come back here.

You can test our new function when you send the following JSON as a POST request to http://localhost:8000/graphql:

{
"operationName": null,
"query": "{
posts {
id
text
}
}",
"variables": {}
}

The operationName field is not required to run a query, but it is great for logging purposes.

The query object is a JSON-like representation of the query we want to execute. In this example, we run the RootQuery posts and request the id and text fields of every post. We do not need to specify RootQuery because it is the highest layer of our GraphQL API.

The variables property can hold parameters such as user the ids by which we want to filter the posts, for example. If you want to use variables, they need to be defined in the query by their name too.

For developers who are not used to tools like Postman, there is also the option to open the GraphQL endpoint in a separate browser tab. You will be presented with a GraphQLi instance made for sending queries easily. Here, you can insert the content of the query property and hit the play button. Because we set up Helmet to secure our application, we need to deactivate it in development. Otherwise, the GraphQLi instance is not going to work. Just wrap the Helmet initialization inside this if statement:

if(process.env.NODE_ENV === 'development')

This short condition only activates Helmet when the environment is in development. Now you can send the request with GraphQLi or any HTTP client.

The resulting answer of POST should look like the following code snippet:

{
"data": {
"posts": []
}
}

We received the empty posts array as expected.

Going further, we want to respond with the fake data we statically wrote in our client to come from our back end. Copy the posts array from App.js above the resolvers object. We can respond to the GraphQL request with this filled posts array.

Replace the content of the posts function in the GraphQL resolvers with this:

return posts;

You can rerun the POST request and receive both fake posts. Apparently, the response does not include the user object we have in our fake data. We must define a user property on the post type in our schema to fix this issue.