Implementing Resolvers

1. Understanding Resolver Function

SignatureDetail
(parent, args, context, info)Standard 4-arg form
ReturnsValue, Promise, AsyncIterator (subs)
DefaultIf omitted, returns parent[fieldName]

2. Implementing Field Resolvers

Example: Field resolver map

const resolvers = {
  Query: { user: (_, { id }, { db }) => db.user.findUnique({ where: { id } }) },
  User: {
    posts: (parent, _, { db }) => db.post.findMany({ where: { authorId: parent.id } }),
    fullName: (parent) => `${parent.firstName} ${parent.lastName}`
  }
};

3. Using Parent Argument

Aliasesparent / root / source
Top-level (Query/Mutation)Usually undefined or rootValue
Nested fieldsResult of parent field's resolver
Mutationundefined at root

4. Using Args Argument

PropertyDetail
TypePlain object with declared field args
CoercionAlready coerced to GraphQL types
DefaultsApplied automatically

5. Using Context Argument

Example: Context with auth + DB

const server = new ApolloServer({
  schema,
  context: async ({ req }) => ({
    user: await verifyJWT(req.headers.authorization),
    db: prisma,
    loaders: createLoaders()
  })
});

6. Using Info Argument

PropertyUse
fieldNameCurrently resolving field
fieldNodesAST of selection
pathFull response path
schemaReference to GraphQLSchema
parentTypeOwning type
variableValuesOperation variables

7. Returning Resolver Values

ReturnEffect
ValueUsed directly
PromiseAwaited
nullField becomes null (or errors if non-null)
ThrowField becomes null + error in errors[]

8. Implementing Default Resolvers

BehaviorDetail
Property lookupparent[fieldName]
FunctionIf property is a function, called with (args, ctx, info)
OverrideProvide explicit resolver to customize

9. Chaining Resolvers

Example: Resolver chain

// Query.user → User.posts → Post.author → User.posts...
// Each level resolves before its children execute.
// Use DataLoader to batch sibling requests.

10. Using Async Resolvers

PatternDetail
async/awaitPreferred
Promise.allParallelize independent fetches
DataLoaderBatch within an event-loop tick

11. Implementing Computed Fields

Example: Computed field

User: {
  fullName: (u) => `${u.firstName} ${u.lastName}`,
  age: (u) => Math.floor((Date.now() - u.dob) / 31557600000)
}

12. Mapping Data Sources

SourcePattern
SQLPrisma, Knex, TypeORM
RESTRESTDataSource (Apollo)
gRPCStub call inside resolver
CacheRedis fronted, write-through