Passing Arguments to Queries
Learn how to implement more complex resolvers that accept arguments.
Parameters in GraphQL queries
To see how we can handle parameters using Apollo Server, we’ll add a new query to our API that allows us to get all the products published by a single author.
type Query {appName: StringallProducts: [Product!]!# New queryproductsByAuthor(authorName: String!): [Product!]!}
The main difference between this new query and the previous queries we’ve implemented is that it receives a single parameter called authorName
of type String!
.
To implement the new query, we need to add a new resolver in our application, which is just a bit more complicated than the resolvers that we have written previously.
const resolvers = {Query: {...// A resolver for the new queryproductsByAuthor: (_, args) => {const user = usersData.find(user => user.userName === args.authorName)return productsData.filter(product => product.authorId === user.id)}},}
To access the arguments passed to the productByAuthor
query, we should use the second parameter, which is called args
in the resolver function. This parameter will contain an object where each field contains a separate argument passed to a query.
productsByAuthor: (_, args) => {...}
For example, let’s try sending the following GraphQL query:
query {productsByAuthor(authorName: "peter")}
Apollo Server will pass the ...