GraphQL conditiontal Filter
Asked Answered
D

1

9

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.

Doublequick answered 31/10, 2017 at 5:24 Comment(0)
L
11

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.

Landloper answered 31/10, 2017 at 11:31 Comment(1)
Thank you so much. I did not know variables did not have to be scalars! I had a hack in javascript where I would make the favorited variable be undefined (not null) and it would behave the way I want it to. I think if a variable is undefined then it is simply ignored. This is much better. I'm using GraphqlCool so this is quite easy. I just have to give the $photoFilter the type of PhotoFIlter.Doublequick

© 2022 - 2024 — McMap. All rights reserved.