Funk Soul Ninja
Funk Soul Ninja

Reputation: 2193

GraphQL conditiontal Filter

Using a GraphCool backend, is there a way to have conditional filter in a query?

let's say I have a query like this:

query ($first: Int, $skip: Int, $favorited: Boolean) {
  allPhotos (
    first: $first
    skip: $skip
    filter: {
      favorited: $favorited
    }
  )
  {
    id
    url
    title
    favorited
  }
}

//variables: { "first": 10, "skip", "favorited": true }

The query above would either:

1) Fetch only photos that are favorited.

2) Fetch only photos that are not favorited.

My problem is I want to be able to either:

1) query photos that are ONLY either favorited OR not favorited.

2) query photos regardless of whether or not they're favorited.

How do I conditionally include filters? Can I? I'm doing something with react-apollo in Javascript and I could figure out a solution with code, but I was wondering if there was a way to do it in graphql land.

Upvotes: 9

Views: 9430

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84857

GraphQL variables don't necessarily have to be scalars -- they can be input types as well. So your query could look like this:

query ($first: Int, $skip: Int, $filter: PhotoFilter) {
  allPhotos (
    first: $first
    skip: $skip
    filter: $filter
  )
  {
    #requested fields
  }
}

The variables you pass along with your query will now include an Object (i.e. { favorited: true }) for filter instead of a boolean for favorited.

To cover all three of your scenarios, send either:

  1. { favorited: true }
  2. { favorited: false }
  3. {} (no filters)

Edit: I think the name of the input type in this case would be PhotoFilter but you may want to double check your schema to be sure.

Upvotes: 11

Related Questions