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

Using multiples types in GraphQL schemas

Let's create a User type and use it with our posts. First, add it somewhere to the schema:

type User {
avatar: String
username: String
}

Now that we have a User type, we need to use it inside the Post type. Add it to the Post type as follows:

user: User

The user field allows us to have a sub-object inside our posts with the post's author information.

Our extended query to test this looks like the following:

"query":"{
posts {
id
text
user {
avatar
username
}
}
}"

You cannot just specify the user as a property of the query. Instead, you need to provide a sub-selection of fields. This is required whenever you have multiple GraphQL types stacked inside each other. Then, you need to select the fields your result should contain.

Running the updated query gives us the fake data, which we already have in our front end code; just the posts array as it is.

We have made good progress with querying data, but we also want to be able to add and change data.