0
0
GraphQLquery~5 mins

Default resolvers in GraphQL

Choose your learning style9 modes available
Introduction

Default resolvers help GraphQL find and return data automatically without extra code.

When you want GraphQL to fetch simple fields from your data without writing custom code.
When your data structure matches your GraphQL schema fields directly.
When you want to quickly set up a GraphQL API that returns data from objects or databases.
When you want to avoid writing resolver functions for every field in your schema.
Syntax
GraphQL
No special code needed. GraphQL uses default resolvers automatically for fields that match your data.
Default resolvers work by matching field names in your schema to keys in your data objects.
If a field needs special handling, you can write a custom resolver to override the default.
Examples
If your data for user is { id: "1", name: "Anna" }, GraphQL returns these fields automatically.
GraphQL
type User {
  id: ID
  name: String
}

type Query {
  user: User
}
Default resolvers fetch id and name from the user object by matching field names.
GraphQL
const user = { id: "1", name: "Anna" };

// GraphQL default resolver returns user.id and user.name without extra code
Sample Program

This GraphQL schema defines a User type and a user query. The resolver returns userData. Default resolvers automatically return id and name from userData.

GraphQL
type User {
  id: ID
  name: String
}

type Query {
  user: User
}

const userData = { id: "1", name: "Anna" };

const resolvers = {
  Query: {
    user: () => userData
  }
};
OutputSuccess
Important Notes

Default resolvers only work when your data keys match your schema fields exactly.

If a field is a function or needs transformation, default resolvers won't work and you must write custom resolvers.

Summary

Default resolvers automatically return data by matching schema fields to data keys.

They save time by avoiding writing simple resolver functions.

Use custom resolvers when you need special data processing.