Search code examples
graphqlapollo

How to create/Fetch data dynamically by filters and order in GraphQL?


I am creating a query in graphql + apollo client whose filters and orders can change depending on what the customer selects in the frontend. For example:

query (
        $orderPart: String!
        $wherePart: String!
        ) {
    getProductInfo(
        order {$orderPart}
        where {$wherePart}
    ) {
      productID
      description
      size
      model
      cathegoryNumber
    }

Where $orderPart will be equal to "description: DESC" or "productID: ASC" (depending what the customer selected in a momento or another). And $wherePart will be equal to "cathegoryNumber: {eq: 12}" or "productID: {eq: 111111}".

I need to pass the order/filter clause completely as a parameter.

But it doesn't work. Syntax is error "Syntax Error: Expected name, found $".

So my question is...

Is there any way to implement these dynamic filters/orders? How could this functionality be implemented? Is there any other way to implement this dynamic filters and orders?

Thanks.

Note: In the official documentation, I found that only values can be passed as a parameters:

query (
        $orderValue: sortEnumType! = DESC
        $whereValue: String! = "description1"
        ) {
    getProductInfo(
        order {productID: $orderValue}
        where {description: {eq: $whereValue} }
    ) {
      productID
      description
      size
      model
      cathegoryNumber
    }

But that is not what I need because always filters/orders couldn't be changed. And they could be completely different each time (prodyuct:ASC) first time, (cathegoryNumber:DESC) second time, etc...


Solution

  • Thanks for your help, I found a solution. Using apollo client and variables when the template is created:

    let orderValue = 'order {productID: ASC}'; // built dynamically
    let whereValue = 'description: {eq: "description1"}'; // built dynamically
    
    document = gql`
    query {
        getProductInfo(
            ${orderValue}
            ${whereValue}
        ) {
          productID
          description
          size
          model
          categoryNumber
        }
        `;