...

/

Passing Arguments to Queries

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.

Press + to interact
type Query {
appName: String
allProducts: [Product!]!
# New query
productsByAuthor(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.

Press + to interact
const resolvers = {
Query: {
...
// A resolver for the new query
productsByAuthor: (_, 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.

Press + to interact
productsByAuthor: (_, args) => {
...
}

For example, let’s try sending the following GraphQL query:

Press + to interact
query {
productsByAuthor(authorName: "peter")
}

Apollo Server will pass the ...