GraphQL by Example: Resolvers
Implementing data fetching logic with this sample code demonstrating resolver function structure, four resolver arguments including parent and args, resolver mapping matching schema structure, and trivial resolution for matching properties.
Code
const users = [
{ id: '1', name: 'Alice' },
{ id: '2', name: 'Bob' }
];
const resolvers = {
Query: {
// Resolver for 'users' field
users: () => users,
// Resolver for 'user' field
// (parent, args, context, info)
user: (parent, args) => {
return users.find(u => u.id === args.id);
}
},
// Resolver for a specific type
User: {
// Computed field
nameUppercase: (parent) => {
return parent.name.toUpperCase();
}
}
};Explanation
Resolvers are functions responsible for populating data for single fields in GraphQL schemas, defining where data comes from rather than just its shape. Every field on every type in a GraphQL schema is backed by a resolver function written by server developers. The resolver map structure matches the schema type structure, with resolvers organized by type name.
Resolver function parameters include:
parentcontains the result of the previous resolver in the chainargscontains the arguments provided in the query for this fieldcontextcontains shared state like authentication tokens or database connectionsinfocontains metadata about the query execution and field information
If field names in the schema match property names in JavaScript objects returned by parent resolvers, explicit resolvers are unnecessary as GraphQL handles this "trivial resolution" automatically. Resolvers are only needed for fields requiring logic, computation, or fetching data from different sources. Resolvers can fetch data from databases, other APIs, or microservices, and can execute asynchronously using promises or async/await.
Code Breakdown
Query: { ... } contains resolvers for top-level fields in Query type.(parent, args) resolver parameters, access id argument via args.id.User: { ... } type-specific resolvers for computed or virtual fields.nameUppercase virtual field computed on-the-fly, not in database.
