BudiBadu Logo
Samplebadu

GraphQL by Example: Resolvers

June 2018 Specification

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:

  • parent contains the result of the previous resolver in the chain
  • args contains the arguments provided in the query for this field
  • context contains shared state like authentication tokens or database connections
  • info contains 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

7
Query: { ... } contains resolvers for top-level fields in Query type.
13
(parent, args) resolver parameters, access id argument via args.id.
19
User: { ... } type-specific resolvers for computed or virtual fields.
21
nameUppercase virtual field computed on-the-fly, not in database.