使用 React 和 Apollo 我有这样的突变:
const UPDATE_USER = gql`
mutation UpdateUser($id: ID!, $someValue: String!, $someOtherValue: String!) {
updateUser(id: $id, someValue: $someValue, someOtherValue: $someOtherValue) {
id
name
}
}
`;
const [mutateUser] = useMutation(UPDATE_USER, {
variables: { id: 123, someValue: 'Hello', someOtherValue: 'World' },
});
工作完美,但
UpdateUser
突变现在只是传递参数,这对我来说似乎不太干燥。
我想知道是否有一种方法可以缩短代码或使其更易于管理,这样当添加另一个参数时,我就不必重新输入 4 次。
如果您有权访问 api,则可以对其进行稍微不同的定义:
const UPDATE_USER = gql`
mutation UpdateUser($data: UpdateUserInput!) {
updateUser(data: $UpdateUserInput: $someOtherValue) {
id
name
}
}
`;
const [mutateUser] = useMutation(UPDATE_USER, {
variables: { data: { id: 123, someValue: 'Hello', someOtherValue: 'World' }},
});
然后在你的API中:
//User.type.js
//Note that this code depends on how you integrated your graphql solution. But the logic is here
const UpdateUserInputType = new GraphQLInputObjectType({
name: "UpdateUserInput",
fields: () => ({
id: { type: new GraphQLNonNull(GraphQLID) },
someValue: { type: new GraphQLNonNull(GraphQLNonNegativeInt) },
SomeOtherValue: { type: GraphQLID },
}),
});
然后将 UpdateUserInputType 添加到解析器的数据变量中