Apollo 客户端:未定义变量。收到状态码 400

Apollo Client: Variable is not defined. Received status code 400

我正在尝试使用 Apollo Client 在 GraphQL 查询中使用动态变量。我已经按照文档进行操作,但是 Apollo 一直报错,说我的变量没有定义,最后返回状态码 400。

Apollo 的文档是这样说的:

mutate: (options?: MutationOptions) => Promise A function to trigger a mutation from your UI. You can optionally pass variables, optimisticResponse, refetchQueries, and update in as options, which will override any props passed to the Mutation component. The function returns a promise that fulfills with your mutation result.

这是我尝试编写的代码:

const fetch = require('node-fetch');
const ApolloClient = require('apollo-boost').default;
const gql = require('graphql-tag');

const client = new ApolloClient({
    uri: "http://api.domain.com/graphql",
    fetch
});

run();

async function run() {
    try {
        const resp = await client.mutate({
            mutation: gql`mutation {
                trackPr(id: $id, pr: $pr, title: $title, body: $body, state: $state, merged: $merged) {
                    id
                }
            }`,
            variables: {
                id: 1,
                pr: 1,
                title: "test title",
                body: "test body",
                state: "test state",
                merged: false
            },
        });


        console.log(resp.data);
    } catch(ex) {
        console.log(ex);
    }
}

然后我会收到每个变量的错误消息,说明它尚未定义:

[GraphQL error]: Message: Variable "$id" is not defined., Location: [object Object],[object Object], Path: undefined

在每条错误消息之后,我都会收到一条状态代码为 400 的最终消息:

[Network error]: ServerError: Response not successful: Received status code 400

突变本身在没有变量和所有直接在突变中设置的值的情况下运行良好,但我不知道为什么它认为变量未定义。

操作中使用的任何变量都必须声明为操作定义的一部分,如下所示:

mutation SomeOptionalMutationName ($id: ID!) {
  trackPr(id: $id) {
    id
  }
}

这允许 GraphQL 根据提供的类型验证您的变量,并验证变量是否被用于代替正确的输入。