Reputation: 545
I'm setting up a GraphQL server using the Apollo framework.
It will have an entity called Shelf
. A Shelf
has a shelfId
and packages
.
I need to be able to query for Shelves
with the shelfId
or packageCode
.
My data source can handle both of these scenario's but I want to have 1 resolver called shelf
for this.
Example
query getShelf(shelfId: "1") {
shelfId
}
or:
query getShelf(packageCode: "123") {
shelfId
}
How to can I define a type the checks if packageCode
or shelfId
is set?
packageCode
is provided shelfId
is not requiredshelfId
is provided packageCode
is not requiredThe only options I think I have are:
How would I proceed?
Upvotes: 3
Views: 1008
Reputation: 2523
You can handle it with one resolver. Above mentioned answer by Daniel is also one of the ways.
You can have both as separate arguments as well.
type Query {
getShelf(SHELF_ID: ID, PACKAGE_CODE:ID)
}
In the resolver, you can check which argument is present and write logic to fetch the data accordingly.
Upvotes: 1
Reputation: 84687
There is no syntax at this time that would support making one of two arguments non-null. You'd have to make both arguments nullable and then add the validation logic to your resolver.
Alternatively, if both arguments are the same type, you can do something like this:
type Query {
getShelf(id: ID! idType: ShelfIdType!)
}
enum ShelfIdType {
SHELF_ID
PACKAGE_CODE
}
I don't think that's necessarily better, but it is an option if you want to rely exclusively on GraphQL's type system for validation.
Upvotes: 2