Search code examples
typesgraphqlapollo

Creating conditional properties in GraphQL type definition


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?

  • When packageCode is provided shelfId is not required
  • When shelfId is provided packageCode is not required
  • When neither us provided either of them are required

The only options I think I have are:

  • A) Create separate resolvers for each scenario
  • B) Make them both optional and return an error from the resolver.

How would I proceed?


Solution

  • 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.