javascriptgraphqlreact-apollographql-codegen

Does GQL support spreading / composing objects (eg. input args)?


I did not find anything about it in the Docs, but for me it seems to be a very common task, so is there a possibility/syntax or a workaround to achieve the following?

My GraphQL query looks something like this:

query customerPersons(
  $pagination: PaginationInput!
  $filter: FilterPersonInput
) {
  persons(pagination: $pagination, filter: $filter) {
    totalCount
    data {
      ...PersonsData
    }
  }
}

With apollo and its codegen I get some helper React Hook function calls, which I can use like this:

const { data } = useCustomerPersonsQuery({
  variables: {
    pagination: {
      skip: 0,
      take: 20,
    },
    filter: {
      query: 'peterchen',
      userType: 'Customer'
    }
  });

Is it possible to move the userType: 'Customer' part into the static part of my query? If it would be JavaScript I would say it is assign or merge two objects with the spread operator. Something like:

query customerPersons(
  $pagination: PaginationInput!
  $filter: FilterPersonInput
) {
  persons(pagination: $pagination, filter: { ...$filter, userType: "Customer" }) {
    totalCount
    data {
      ...PersonsData
    }
  }
}

Solution

  • No, GraphQL does not support such syntax in query documents. The closest you could achieve would be creating separate variables for all the fields in FilterPersonInput other than userType.

    The two solutions available are: