简体   繁体   English

Apollo 客户端查询缺少字段 __typename

[英]Apollo Client query ​Missing field __typename

I am trying to use apollo-link-rest with the Star Wars API and I am getting some errors.我正在尝试将apollo-link-rest与 Star Wars API 一起使用,但出现了一些错误。

import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloClient } from "apollo-client";
import { RestLink } from "apollo-link-rest";
import gql from "graphql-tag";

// node environment?
const fetch = require("node-fetch");
global.fetch = fetch;
global.Headers = fetch.Headers;

const restLink = new RestLink({
  endpoints: { swapi: "https://swapi.co/api/" }
});

const client = new ApolloClient({
  link: restLink,
  cache: new InMemoryCache()
});

const query = gql`
  query people {
    search
      @rest(type: "Search", path: "people/?search=skywalker", endpoint: swapi) {
      count
      results {
        name
      }
    }
  }
`;

client
  .query({ query })
  .then(response => console.log(JSON.stringify(response)))
  .catch(err => console.log(err));

Errors:错误:

​​​Missing field __typename in {​​​
​​​  "name": "Luke Skywalker"​​​
​​​}​​​
​​​​​​
​​​Missing field __typename in {​​​
​​​  "name": "Anakin Skywalker"​​​
​​​}​​​
​​​​​​
​​​Missing field __typename in {​​​
​​​  "name": "Shmi Skywalker"​​​
​​​}​​​

I know I can change set this InMemoryCache({ addTypename: false }) to remove the errors, but I don't know what the impact on caching will be if I set addTypename to false .我知道我可以更改设置此InMemoryCache({ addTypename: false })以消除错误,但我不知道如果将addTypename设置为false会对缓存产生什么影响。

Can someone point me in the right direction on this?有人能指出我正确的方向吗?

Cheers!干杯!

Check out what the docs have to say about typename patching .查看文档对typename patching 的看法。

Your @rest directive tells the client what typename to expect for the search field, but doesn't say anything about any types inside the field's selection set.您的@rest指令告诉客户端search字段的类型名称,但没有说明该字段选择集中的任何类型。 There's two ways to fix that.有两种方法可以解决这个问题。 You can use a @type directive:您可以使用@type指令:

query people {
  search @rest(type: "Search", path: "people/?search=skywalker", endpoint: swapi) {
    count
    results @type(name: "Person") {
      name
    }
  }
}

Or configure a typePatcher .或者配置一个typePatcher Something like:就像是:

const restLink = new RestLink({
  uri: 'https://swapi.co/api/',
  typePatcher: {
    Search: (data, outerType, patchDeeper) => {
      if (data.results != null) {
        data.results = data.results.map(person => {
          return {__typename: "Person", ...person }
        });
      }
      return data
    },
  },
})

More generic answer:更通用的答案:

to avoid the missing __typename error ensure any arrays in your GQL model has a corresponding field __typename for EACH object in the array.为避免missing __typename错误,请确保 GQL 模型中的任何数组对于数组中的每个对象都具有相应的字段__typename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM