In order to allow resolvers to return partial data and have other resolvers complete the missing fields, I follow this convention:
type UserExtra {
name: String!
}
type User {
id: ID!
email: String!
extra: UserExtra!
}
type Query {
user(id: ID!): User!
users: [User!]!
}
const getUser = (id: string): { id: string, email: string, extra: { name: string } => fetchUser(id);
// `fetchUsers` only returns `id` and `email`, but not `extra`
const getUsers = (): { id: string, email: string }[] => fetchUsers();
// we can use this function to fetch the extra field for a given user
const getUserExtra = (id: string): { name: string } => fetchUserExtra();
export default {
Query: {
user: (parent, args) => getUser(args.id),
users: () => getUsers(),
},
User: {
// here we fetch the `extra` field anytime an `User` is requested
// in real-life I would check if the query is requesting the `extra`
// field or not, and only fetch the data if requested by the query
extra: (parent) => {
return getUserExtra(parent.id)
},
}
}
I am faced with a challenge where GraphQL Code Generator expects the Resolver
type to have Query#users
return the complete shape of User
, even though it may be returned partially due to User#extra
eventually completing the shape for the client.
To address this issue while satisfying TypeScript requirements, what approach should I take?