In this tutorial, we will learn how to create Query and Mutation resolvers, which are fundamental components of a GraphQL server.
You will learn:
- The roles of Query and Mutation resolvers in a GraphQL API
- How to create Query resolvers to fetch data
- How to create Mutation resolvers to modify data
Prerequisites:
- Basic knowledge of JavaScript
- Familiarity with GraphQL and its syntax
Resolvers in GraphQL are functions that resolve data for your GraphQL fields in the schema. They're responsible for the process of combining your schema, your query, and your data source information to return the requested data.
Query resolvers fetch data from your database and return it to your GraphQL server. They are responsible for reading data.
Mutation resolvers, on the other hand, are responsible for creating, updating, and deleting data.
Here's an example of a Query resolver and a Mutation resolver for a simple user system.
// The users Query resolver
const resolvers = {
Query: {
users: async () => {
// fetch all users from the database
const users = await User.find();
// return the users
return users;
},
},
};
This code defines a Query resolver for fetching all users. The resolver is an async function that fetches all users from the database using the User.find()
function and then returns them.
// The createUser Mutation resolver
const resolvers = {
Mutation: {
createUser: async (parent, args) => {
// create a new user with the provided input
const newUser = new User(args);
// save the user to the database
await newUser.save();
// return the new user
return newUser;
},
},
};
This code defines a Mutation resolver for creating a new user. The resolver is an async function that creates a new user with the provided arguments, saves the user to the database using the newUser.save()
function, and then returns the new user.
In this tutorial, we covered the basics of creating Query and Mutation resolvers in GraphQL. We learned that Query resolvers are for fetching data and Mutation resolvers are for modifying data.
To learn more, you can look into how to handle errors in your resolvers, how to use context in your resolvers, and how to create more complex resolvers.
Solutions:
const resolvers = {
Query: {
user: async (parent, args) => {
const user = await User.findById(args.id);
return user;
},
},
};
const resolvers = {
Mutation: {
updateUser: async (parent, args) => {
const updatedUser = await User.findByIdAndUpdate(args.id, args, { new: true });
return updatedUser;
},
},
};
const resolvers = {
Mutation: {
deleteUser: async (parent, args) => {
const deletedUser = await User.findByIdAndDelete(args.id);
return deletedUser;
},
},
};
Each of these exercises will help you understand how to work with resolvers better and make you more comfortable with them. Happy coding!