GraphQL 保存表单

GraphQL Save a form

我想通过 GrahQL 和 React 保存一个大表单。 我在一个变量名称中包含所有表单值:formValue 有没有办法像这样将“formValue”传递给查询?

const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })

const SAVE_USER_PROFILE = gql`
  mutation saveUserProfile($profileId: String!) {
    updateProfile(profile: { formValue }) {
     id
    }
  }
`

或者我应该将所有字段一一传递并像这样定义它们的类型?

const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })

const SAVE_USER_PROFILE = gql`
  mutation saveUserProfile($id: String!, $firstName: String, $lastName: String, $age: Int, ......) {
    updateProfile(profile: { id: $id, firstName: $firstName, lastName: $lastName, age:$age, ......}) {
      id
    }
  }
`

架构看起来像这样

updateProfile(profile: ProfileDTOInput!): ProfileDTO

type ProfileDTO {
  address: String
  emails: String
  employeeId: String
  firstName: String
  lastName: String
  age: Int
  phone: [PhoneDTO]
}

input ProfileDTOInput {
  lastName: String
  phone: [PhoneDTO] 
  address: String
  age: Int
  employeeId: String
  emails: String
  firstName: String
} 

type PhoneDTO {
  number: String
  phoneType: String
}

input PhoneDTOInput {
  phoneType: String
  number: String
}

对于这种情况,您应该使用 GraphQL 输入类型。为什么? GraphQL 输入类型对于保持参数定义简洁明了很有用,尤其是在像您这样的情况下。例如,这个:

mutation saveUserProfile($id: String!, $firstName: String, $lastName: String, $age: Int, ......)

有可能扩展到您定义的突变的无穷无尽的参数列表。这不仅难以编写,而且也难以维护和阅读。

相反,使用输入类型会大大简化这一过程。

input SaveUserProfileInput {
  id: ID!
  firstName: String
  lastName: String
  ...
}

mutation saveUserProfile($input: SaveUserProfileInput!) {
  updateProfile(input: $input) {
    ...rest of your code here...
  }
}

您的突变现在只需要一个参数——一种输入类型——它是自己定义的。作为模式设计者,您可以在一个地方随心所欲地扩展这些字段。您的变更定义及其采用的参数永远不需要更改。

请注意,如果您遵循此操作,您需要更改突变 updateProfile 的架构定义以接受输入作为类型 SaveUserProfileInput(或您命名的任何名称)的参数方法。

有关输入类型的更多信息,我建议查看 Daniel Rearden 的精彩 post: