1

I'm using Apollo to make requests to my GraphQL server.

My query is like below:

export const QUERY_ITEMS = gql`
    query get_items($date: date) {
        items(where: {date: {_eq: $date}}) {
            name
        }
    }
`;

const {data} = useQuery(QUERY_ITEMS, variable: {date: '2020-01-01'});

Notice how right now the _eq operator is hardcoded. I'm implementing a feature where I'm making that operator dynamic to enable things like '_gt' and '_lt' .How can I achieve this?

7ball
  • 2,183
  • 4
  • 26
  • 61

2 Answers2

1

gql can receive placeholder variable

function gql(literals: any, ...placeholders: any[]): any;

so you can use something like this

export const QUERY_ITEMS = (placeholder) => gql`
    query get_items($date: date) {
        items(where: {date: {${placeholder}: $date}}) {
            name
        }
    }
`;
Alex
  • 3,941
  • 1
  • 17
  • 24
1

Rather than passing in the date as a variable, you can pass in the entire expression

query get_items($exp: SomeType) {
  items(where: { date: $exp }) {
    name
  }
}

or the entire argument

query get_items($where: SomeOtherType) {
  items(where: $where) {
    name
  }
}

The types you use for your variable are schema-specific -- you can look up information about the schema Hasura generates in the GraphiQL interface available through the console (just search for the field name).

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183