GraphQL
Resolvers
Functions that fulfill each field.
By EZ4Code Team
resolverfunction
Code
const resolvers = {
Query: {
book: (parent, { id }, { db }) => db.books.findById(id),
books: (parent, { limit = 10 }, { db }) =>
db.books.findAll({ limit }),
},
Mutation: {
createBook: (parent, { input }, { db, user }) =>
db.books.create({ ...input, authorId: user.id }),
},
Book: {
author: (book, args, { db }) => db.authors.findById(book.authorId),
},
Author: {
books: (author, args, { db }) => db.books.findByAuthor(author.id),
},
};Explanation
Resolvers are functions that return the data for a single schema field, receiving the parent object, arguments, and a shared context. Field-level resolvers let you fetch relations lazily and switch data sources per field. The context typically carries the database connection and authenticated user so resolvers stay pure.