What is Default Resolver in GraphQL: Explanation and Example
default resolver is the built-in function that automatically fetches the value of a field by looking up the property with the same name on the parent object. It runs when you don't provide a custom resolver for a field, making it easy to return simple data without extra code.How It Works
Imagine you have a box labeled with different compartments, each holding a specific item. When you ask for an item by name, the default resolver simply opens the compartment with that name and hands you the item inside. In GraphQL, when a query asks for a field, the default resolver looks for a property with the same name on the object returned by the parent field.
This means if your data is already shaped like your GraphQL schema, you don't need to write extra code to fetch each field. The default resolver automatically returns the value it finds, saving time and effort. If the field is a function, it calls it; if it's a simple value, it returns it directly.
Example
This example shows a simple GraphQL schema and how the default resolver returns data without custom code.
const { graphql, buildSchema } = require('graphql'); // Define schema with a type 'User' having fields 'id' and 'name' const schema = buildSchema(` type User { id: ID name: String } type Query { user: User } `); // Root provides data matching the schema shape const root = { user: { id: '1', name: 'Alice' } }; // Query asks for user id and name const query = `{ user { id name } }`; // Run the query graphql(schema, query, root).then((response) => { console.log(response); });
When to Use
Use the default resolver when your data objects already have properties that match your GraphQL schema fields. This is common when your data comes from simple objects, like JSON or database records, and you want to quickly expose them through GraphQL without writing extra code.
For example, if you have a user object with fields like id and name, and your schema matches those fields, the default resolver handles fetching them automatically. You only need custom resolvers when you want to compute values, fetch from different sources, or apply special logic.
Key Points
- The default resolver looks up a field by name on the parent object.
- It works automatically for simple data structures matching the schema.
- No need to write custom code for straightforward data fetching.
- Custom resolvers are needed only for complex logic or data fetching.