Today I Learned

Skip graphQL field based on variable

GraphQL allows to conditionally include or exclude some fields using @skip and @unless keywords.

example:

query(
  $limit: Int
  $offset: Int
  $withExpiredBookings: Boolean = false // default value
  // $withoutExpiredBookings: Boolean = true
) {
  users(
    limit: $limit
    offset: $offset
  ) {
    totalCount
    nodes {
      id
      name
      email
      hasBookingsAfterDocumentsExpiration @include(if: $withExpiredBookings)
      // or
      // hasBookingsAfterDocumentsExpiration @skip(if: $withoutExpiredBookings)
      region {
        id
        name
        timezone
        countryCode
      }
    }
  }
}

// hook usage
useQuery(USERS_QUERY, {
  variables: {
    withExpiredBookings: countryCode === 'gb',
  },
}),

// HOC usage
export default graphql(USERS_QUERY, {
  options: (ownProps) => ({
    variables: {
      withExpiredBookings: ownProps.countryCode === 'gb',
    },
  }),
})(Component),

See more at: https://www.apollographql.com/docs/apollo-server/schema/directives/