1

I am trying to create a graphql query where the query data type and filter parameters will be passed dynamically based on user input.

I have written the below query which filters using only one field shipdate.

const GET_SHIPDATA_WITH_FILTER = gql`
  query GetShipData($shipdateStart: timestamptz, $shipdateEnd: timestamptz, $limit: Int) {
    shipdata(where: {shipdate: { _gte: $shipdateStart, _lte: $shipdateEnd}},limit: $limit) {
      status
      import_time
      shipdate
    }
  }
`;

const variables = {
  shipdateStart: "some date",
  shipdateEnd: "some date",
  limit: 50,
};

If no filter is passed I'm using this one

const GET_SHIPDATA = gql`
  query GetShipData($limit: Int) {
    shipdata(limit: $limit) {
      status
      import_time
      shipdate
    }
  }
`;
const variables = {
  limit: 50,
};

You can see I have written two queries to handle two types of filters which won't work if I want to add more filters.

Now I am trying to write a single dynamic query where if the user wants to add more filters like status: {_eq: $status} or import_time: { _gt: $importTimeStart, _lt: $importTimeEnd} then I will pass the variables and the query will dynamically handle the filters. Something like

const GET_SHIPDATA = gql`
  query GetShipData($allfilters: AllFilterTypes) {
    shipdata(filter: $allfilters) {
      status
      import_time
      shipdate
    }
  }
`;
const variables = {
  //pass allFilters based on user input,
};

Btw I'm using react and hasura if it helps anyway.

1 Answer 1

1

Hasura already exposes types in your GraphQL schema that refer to "filter conditions". In Hasura, they're called Bool_Exp (short for boolean expression) and they map directly to the where clause.

If you just update your query to receive a shipdata_bool_exp you'll be able to build up a dynamic filter expression in your application code and it will work as expected.

const GET_SHIPDATA_WITH_FILTER = gql`
  query GetShipData($filter: shipdata_bool_exp!) {
    shipdata(where: $filter,limit: $limit) {
      status
      import_time
      shipdate
    }
  }
`;
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please give me an example of how to receive the shipdata_bool_exp and how to pass the filter with _gt or _lt from the variables?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.