官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 阿拉善盟| 武平县| 遵义县| 宕昌县| 宁海县| 金华市| 祥云县| 广南县| 石家庄市| 息烽县| 襄城县| 綦江县| 永年县| 犍为县| 古田县| 宁强县| 土默特右旗| 西丰县| 耿马| 柳河县| 方山县| 鄱阳县| 伊川县| 金秀| 江陵县| 上饶市| 嘉鱼县| 玉田县| 特克斯县| 梁山县| 东源县| 宁安市| 景德镇市| 芦溪县| 万山特区| 象州县| 昌吉市| 安庆市| 镇雄县| 牙克石市| 清新县|