Search code examples
graphqlhasura

in an Hasura query, is it possible to not repeat the where condition when doing an aggregate query


For example the following query:

 query getAttributeValues($language_code: String, $id_attribute: Int, $search: String) {
                v4_bo_v_attribute_values(
                    where: {
                        _and: [
                            { id_attribute: { _eq: $id_attribute } }
                            { _or: [{ language_code: { _eq: $language_code } }, { language_code: { _is_null: true } }] }
                            { _or: [{ attribute_value_translation: { _ilike: $search } }, { attribute_value: { _ilike: $search } }] }
                        ]
                    }
                    order_by: { attribute_value_translation: asc, attribute_value: asc }
                    limit: 100
                ) {
                    attribute_value
                    attribute_value_translation
                }
                v4_bo_v_attribute_values_aggregate(
                    where: {
                        _and: [
                            { id_attribute: { _eq: $id_attribute } }
                            { _or: [{ language_code: { _eq: $language_code } }, { language_code: { _is_null: true } }] }
                            { _or: [{ attribute_value_translation: { _ilike: $search } }, { attribute_value: { _ilike: $search } }] }
                        ]
                    }
                ) {
                    aggregate {
                        count
                    }
                }
            }

Solution

  • We can use variables, even for where condition:

    const searchQuery = search ? `%${search}%` : "%%";
    const query = {       
        query: gql`
            query getAttributeValues($where: v4_bo_v_attribute_values_bool_exp) {
                v4_bo_v_attribute_values(
                    where: $where
                    order_by: { attribute_value_translation: asc, attribute_value: asc }
                    limit: 100
                ) {
                    attribute_value
                    attribute_value_translation
                }
                v4_bo_v_attribute_values_aggregate(
                    where: $where
                ) {
                    aggregate {
                        count
                    }
                }
            }
        `,
        variables: {
            where: {
                _and: [
                    { id_attribute: { _eq: id_attribute } },
                    { _or: [{ language_code: { _eq: tradLanguage } }, { language_code: { _is_null: true } }] },
                    { _or: [{ attribute_value_translation: { _ilike: searchQuery } }, { attribute_value: { _ilike: searchQuery } }] }
                ]
            }
        }