使用 Apollo GraphQL 出现 "Invariant Violation" 错误

Getting "Invariant Violation" error with Apollo GraphQL

我正在使用 Apollo GraphQL,但我是新手,我收到以下错误:

{
    "framesToPop": 1,
    "name": "Invariant Violation"
}

这是我的代码:

const httpLink = createHttpLink({
    uri: "https://api.example.com/v3/ListingsQuery",
    fetch
});
const automaticPersistedQueryLink = createPersistedQueryLink();
const apolloClient = new ApolloClient({
    link: ApolloLink.from([automaticPersistedQueryLink, httpLink]),
    cache: new InMemoryCache()
});
const variables = {
    filters: {statuses: ["ACTIVE", "UNLISTED"]},
    orderBys: [{sortField: "STATUS", sortOrder: "DESC"}],
    shouldFetchHostMultiListingAgendaPermissions: true,
    offset: 0,
    shouldFetchListingPermissions: false,
    count: 15,
    query: null
};
await apolloClient.query({
    query: {},
    variables
});

知道我做错了什么吗?

首先,Apollo 似乎是以“生产模式”而不是“开发模式”启动的。通过以开发模式启动它,Apollo 将为您提供更详细的错误消息。要解决此问题,请将 env.NODE_ENV 设置为 development 来启动您的节点进程。抱歉,如果这不清楚,但我不能在这里更精确,因为确切的过程取决于您的应用程序是如何启动的and/or您正在使用哪个框架...

不过,在最近的版本中,在生产模式下 运行 时,错误消息中应该有一个数字错误代码,例如 Invariant Violation: 42。这些数字错误代码可以更轻松地诊断问题,即使在生产模式下也是如此。确保您使用的是最新版本的@apollo/client(我写这篇文章时最新版本是 3.2.5;请参阅 https://www.npmjs.com/package/@apollo/client)。

现在,关于错误本身...完整的错误消息很可能是 Invariant Violation: You must wrap the query string in a "gql" tag. 这是因为您提供了一个空查询,如下所示:

await apolloClient.query({
    query: {},   // <--- Empty query here
    variables
});

有几种方法可以向 Apollo 客户端提供查询。最简单的方法是将 GraphQL 查询嵌入 JavaScript 源代码中,使用“gql 标签”符号,例如:

await apolloClient.query({
    query: gql`
      query TestQuery {
        launch(id: 56) {
          id
          mission {
            name
          }
        }
      }
    `,
    variables
});

这应该开箱即用,但出于性能原因,您应该在构建过程中添加一个 GraphQL 编译步骤。也许这个过程已经到位(例如,如果您使用诸如 Create React Apps 或 Gatsby 之类的框架开始您的项目......)。请参阅此文档以获取对此的解释 (https://www.apollographql.com/docs/react/performance/babel/)。