来自 GraphQL 突变的动态响应

IT技术 reactjs graphql apollo react-apollo apollo-client
2021-05-08 20:56:01

我正在使用 Apollo-Client 与 GraphQL 后端 (PHP) 一起工作,并且遇到了一些突变问题。

我正在处理的当前组件集是用于用户详细信息的表单。使用查询获取和显示详细信息,并且可以编辑和保存。当用户保存时,会进行检查以确定哪些值已更改,并通过更改发送这些值以进行更新。

我遇到的问题是我只希望从突变返回已更新的数据,因为返回每个可能已更新的字段增加响应时间。有没有办法动态构建突变来决定返回哪些字段?

这是当前状态的突变:

const UPDATE_CLIENT = gql`
mutation updateClient( $data: [ClientInput]! ) {
    add_update_clients( data: $data ) {
        id
        ref
        name {
            title
            firstname
            surname
            preferred_name
        }
        gender
        dob
        nhs_number
        email
        telephone {
            number
        }
        mobile {
            number
        }
        region {
            id
            name
        }
        referral_received
        user_aware_of_referral
        referred_for {
          id
          name
        }
        weekly_hours
        contract_date
        service_start_date
        expected_end_date
        service_end_date
        reason_left
        po_number
        accounting_ref
        country_of_birth {
            id
            name
        }
        nationality {
            id
            name
        }
        ni_number
        place_of_birth
        ethnicity {
            id
            name
        }
        first_language {
            id
            name
        }
        religion {
            id
            name
        }
        marital_status
        dependants
        sexual_orientation
        height
        weight
        hair_colour
        eye_colour
    }
}
`;

和一小段代码提交

const mutation = await client.mutate({
            mutation: UPDATE_CLIENT,
            variables: { data },
            errorPolicy: 'all'
        });

但本质上,如果我更新,dob那么这是我在响应中唯一想要的数据

1个回答

您可以使用@skipor@include指令来指定应从选择集中省略的字段。如果您要跟踪哪些字段已在客户端更新,您可以使用这些值来创建一组变量以传递给您的查询。

mutation updateClient(
  $data: [ClientInput]!
  $includeGender: Boolean = false
  $includeDob: Boolean = false
  $includeEmail: Boolean = false
  # ... and so on
  ) {
  add_update_clients( data: $data ) {
    gender @include(if: $includeGender)
    dob  @include(if: $includeDob)
    email  @include(if: $includeEmail)
    # ... and so on
  }
}