我正在尝试改变突变。该突变确实存在,并且在我的 graphql 游乐场上运行良好。但是当我在我的反应组件中实现它时,我收到错误。不过查询工作正常。顺便说一句,我的代码中需要客户端,所以我肯定必须使用 ApolloConsumer。
我尝试使用 client.mutate https://github.com/apollographql/apollo-client/issues/2762
export const LOGIN = gql`
mutation LOGIN($email: String!, $password: String!) {
login(email: $email, password: $password) {
email
}
}
`;
class LoginComponent extends Component{
render(){
return(
<ApolloConsumer>
{client=>{
return(
<Button onClick={()=>{
client
.mutate({
mutation: LOGIN,
variables: {
email: "[email protected]",
password: "test"
}
})
.then(result => {
console.log('result', result)
})
.catch(err => {
console.log("err", err);
alert(err.toString());
});
}}>
OK
</Button>
)
}}
</ApolloConsumer>
)
}
}
我希望获得成功,但收到错误:GraphQL 错误:无法在“Mutation”类型上查询字段“登录”。 (第 2 行,第 3 列): 登录(电子邮件:$电子邮件,密码:$密码){ ^
同样的问题,我想添加我的 2 美分作为答案:
对于不同 GraphQL 服务器的不同端点,我有几个“上下文”。
我正在使用突变钩子,例如:
const THE_QUERY_OR_MUTATION_CODE = gql`
mutation {
myMutation(etc) {
_id
etc
}
}`
const [handlerOrCaller, { loading, error, data } ] =
useMutation(THE_QUERY_OR_MUTATION_CODE);
以这种方式,我没有给它正确的“上下文”,所以 Apollo 客户端正在获取找到的第一个上下文,这当然是另一个端点,并且模式当然没有称为
myMutation
的突变。
我的 Apollo 客户端的配置是:
const client = new ApolloClient({
cache: new InMemoryCache({
dataIdFromObject: (object) => object.key || null
}),
link: authLink.concat(splitOne)
});
splitOne
是一个用不同端点以这种方式连接的变量:
const endpointALink = createHttpLink({
uri: process.env.REACT_APP_ENDPOINT_A
});
const ednpointBLink = createUploadLink({
uri: process.env.REACT_APP_ENDPOINT_B
});
const endpointCLink = createUploadLink({
uri: process.env.REACT_APP_ENDPOINT_C
});
const endpointDLink = createHttpLink({
uri: process.env.REACT_APP_ENDPOINT_D
});
const splitThree = split(
(operation) => operation.getContext().clientName === 'context_a',
endpointA,
endpointB
);
const splitTwo = split(
(operation) => operation.getContext().clientName === 'context_b',
endpointC,
splitThree
);
const splitOne = split(
(operation) => operation.getContext().clientName === 'context_c',
endpointD,
splitTwo
);
所以,就我而言,正确的方法是使用正确的上下文:
const [handlerOrCaller, { loading, error, data } ] =
useMutation(THE_QUERY_OR_MUTATION_CODE, {
context: { clientName: 'context_c' }
});
我的错误是微不足道的:我在后端使用type-graphql和apollo-server,但在解析器字段中添加了数据源而不是正确的解析器:
const schema = await buildSchema({
resolvers: [
FirstResolver,
SecondResolver,
// added datasource instead of resolver
ThirdDataSource,
FourthResolver,
]})
用解析器替换数据源解决了问题。
套餐版本:
"apollo-datasource": "^3.0.3",
"type-graphql": "^1.1.1",
"apollo-server-core": "^3.6.2",