ChilliCream graphql: using variables to define order_by

58 Views Asked by At

I have a working graphql query:

query orderOnTheFly {
  products(order:{ id: ASC, status: ASC }) 
  {
    nodes { id status }
  }
}

Now I have to implement (on frontend) the user selects which field ( id or status) and which order (ASC or DESC) wants to use (ordering by only one field at a time). What I wanted to write (for example $fieldName="id", $order="ASC" - to let ordering id ASC):

query orderOnTheFly( $fieldName:String, $order:String) {
  products(order:{ $fieldName: $order }) 
  {
    nodes { id status }
  }
}

or at least ($idOrder=null, $statusOrder="ASC" - when I do not select id field into ordering, only by status ASC)

query orderOnTheFly( $idOrder:String, $statusOrder:String) {
  products(order:{ id: $idOrder, status: $statusOrder }) 
  {
    nodes { id status }
  }
}

Neither of them work. How to solve this situation?

The frontend uses react-relay compiler, so I don't want to generate the graphql query with string manipulation. Otherwise - my graphql server is a .net core server with hotChocolate package (and the database is a Marten event store).

1

There are 1 best solutions below

4
Michel Floyd On

The simplest way to avoid generating the query using string manipulation is to write your query to use a variables object for the input. react-relay can "compile" the query and then the variables object can be defined at runtime.