GraphQL
Beginner
1 min read
Resolver Function Anatomy
Example
// Resolver signature: (parent, args, context, info) => value | Promise<value>
const resolvers = {
// Root resolvers — no parent value
Query: {
user: async (_, { id }, { db, currentUser }) => {
if (!currentUser) throw new Error('Unauthenticated');
return db.users.findById(id);
},
posts: async (_, { authorId, limit = 20 }, { db }) => {
return db.posts.findAll({ where: { authorId }, limit });
},
},
// Type resolvers — parent is the resolved User object
User: {
// Computed field: not stored in DB
fullName: (user) => `${user.firstName} ${user.lastName}`,
// Relation: load posts for this user
posts: async (user, { limit }, { db }) => {
return db.posts.findAll({ where: { authorId: user.id }, limit });
},
// Hide sensitive data based on context
email: (user, _, { currentUser }) => {
if (currentUser?.id === user.id || currentUser?.role === 'ADMIN') {
return user.email;
}
return null;
},
},
Post: {
// Resolve author from authorId stored on post
author: (post, _, { db }) => db.users.findById(post.authorId),
wordCount: (post) => post.body.split(/\s+/).length,
},
};
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL