Reputation: 650
I'm adopting GraphQL as my data composition layer for the several backend microservices. We have a UserService
which provides some user-related REST APIs, one is /users
and the other is /detail?userId=${userId}
.
I have the following schema definition:
type User {
userId: ID!
name: String!
address: String
// ... some other fields
}
Query {
users: [User]!
userDetail(userId: ID): User
}
The problem is, for some performance reason, the User
item from /users
has fewer fields than /detail
. For example, the address
field does not exist in the list API, and only exists in the detail API.
So, do we have to define another UserListItem
for the list Query? Due to the backend API limit, we can NOT share the same User
type definition between list and detail query.
Upvotes: 0
Views: 1039
Reputation: 276
First, I think we should think about that why the address field does not exist in the list API ?
In the view of Apollo, same user id should get the same result. So in your situation, it is unreasonable.
If you don’t define another type for list query will cause cache problem (client side)
You can refer to this article for more info
(same id, type different result)
https://kamranicus.com/posts/2018-03-06-graphql-apollo-object-caching
And if you define another type for list query will cause cache problem as well (about client side updating cache after mutation)
Of course, client side can fix cache problem by setting fetchPolicy or updating cache manually, but it is not the best solution.
So if I am backend developer, I will try to put address field in the list API.
If you really can not put address field in the list API, I think define another type is better.
But client side need to pay more attention to updating cache problem.
For example, if we define another type for user. (type UserDetail
)
Suppose that we have a page to display user list (type User
), and we have a mutation to edit user info.
Usually, when we go to the edit page, we will execute userDetail
for initializing form data.(type UserDetail
)
If the return type is User
after mutation then the user have same id in user list will update cache automatically.
(https://www.apollographql.com/docs/react/advanced/caching/#automatic-cache-updates)
But when we back to the edit page, you will find that userDetail's data remain same after mutation because mutation's return type is User
instead of UserDetail
.
In this situation, I will set fetchPolicy to network-only
(userDetail query) and vice versa.
Same id and type but different result
refer to this article
https://kamranicus.com/posts/2018-03-06-graphql-apollo-object-caching
Upvotes: 1