Basic Components: Each resolver in GraphQL is a function that optionally takes four arguments:
root
(or parent
): The result from the previous level of the resolver chain.args
: An object that contains all GraphQL arguments provided in the query.context
: An object shared across all resolvers that executes for a particular query. It often contains per-request state such as authentication information.info
: A field-specific information object useful for advanced cases like building dynamic queries.Example:
const resolvers = {
Query: {
user: (parent, args, context, info) => {
return context.dataSources.userAPI.getUserById(args.id);
}
}
}
For Queries: Fetch data based on the input arguments.
Query: {
posts: (parent, args, context) => context.db.getPosts(),
post: (parent, { id }, context) => context.db.getPostById(id),
}
For Mutations: Perform actions to modify data and return the new state of the data.
Mutation: {
createPost: (parent, { post }, context) => context.db.createPost(post),
deletePost: (parent, { id }, context) => context.db.deletePost(id),
}
Definition and Use: Enums are special scalar types that are restricted to a particular set of allowed values. They help ensure your application uses only predefined values.
Resolver Behavior: Typically, enum values do not require special resolver functions; they are validated by the GraphQL server against the schema and returned directly.
Example:
const resolvers = {
POST_STATUS: {
DRAFT: 'draft',
PUBLISHED: 'live',
INREVIEW: 'in-review'
}
}
Definition and Use: A union is a type that can be one of several types. It's useful when an API can return objects that are not related to each other.
Type Resolver: Essential for GraphQL to know what type each returned object is when it fetches a union.
const resolvers = {
SearchResult: {
__resolveType(obj, context, info) {
if(obj.title) {
return 'Book';
}
if(obj.publicationDate) {
return 'Magazine';
}
if(obj.firstName) {
return 'Author';
}
return null; // Type resolution failed
}
}
}