wp-graphql / wp-graphql-tax-query

Adds `tax_query` support to postObject connection queries using WP_Query
46 stars 16 forks source link

Variable and Combined Query example. #11

Open BartoszLobejko opened 5 years ago

BartoszLobejko commented 5 years ago

Hey, I was struggling to combine few queries together to do more advanced filtering and I found that Directives doesn't work. So I came up with this simple solution to combine tax and meta queries but only include them when needed. Hopefully, that improves performance. (this example also include pagination and fragments)

const ACCOMMODATION_QUERY = (
  first,
  after,
  locationFilter,
  typeFilter,
  ifLocation,
  ifType,
) => gql`
    query AccommodationsQuery(
      $first: Int = ${first}
      $after: String = ${after}
      ${ifLocation ? `$locationFilter: String = "${locationFilter}"` : ``}
      ${ifType ? `$typeFilter: [String] = ["${typeFilter.join('","')}"]` : ``}
    ) {
    accommodations(
      first: $first
      after: $after
      where: {
        orderby: { field: MODIFIED, order: DESC }
        ${
          ifLocation
            ? `metaQuery: {
          metaArray: [{ key: "location", value: $locationFilter, compare: LIKE }]
        }`
            : ``
        }
        ${
          ifType
            ? `taxQuery: {
          taxArray: [
            {
              terms: $typeFilter
              taxonomy: ACCOMMODATIONTYPE
              operator: IN
              field: SLUG
            }
          ]
        }`
            : ``
        }
      }
    ) {
      pageInfo {
        hasNextPage
        endCursor
      }
      edges {
        cursor
        node {
          date
          modified
          slug
          title
          accommodationDetails {
            ...AccommodationListDetails
          }
        }
      }
    }
  }
  ${AccommodationListDetailsFragment}
`;

And then you can skip variables in render

<Query
              query={ACCOMMODATION_QUERY(
                first,
                after,
                locationFilter,
                typeFilter,
                ifLocation,
                ifType,
              )}
              variables={{}}
            >
...
</Query>

Let me know what do you think.