【问题标题】:How to define client side schema in `react-apollo` application?如何在“react-apollo”应用程序中定义客户端模式?
【发布时间】:2020-01-06 19:05:40
【问题描述】:

我在我的反应申请人中使用react-apollo,但我不知道如何实现客户端模式。

我有以下类型定义:

export const alertTypeDefs = gql`
  type Query {
    alert: Alert
  }
  type Alert {
    message: String!
    type: String!
    duration: Int!
  }
`;

它定义了一个Query,它返回一个alert 对象。

下面是我要使用这个查询的代码。

const cache = new InMemoryCache();

export const createClient = () => {
  return new ApolloClient({
    cache,
    typeDefs: [alertTypeDefs]
  });
};

首先,我用内存缓存和上面定义的alertTypeDefs 初始化了一个ApolloClient 实例。然后下面是运行查询的代码:

const client = createClient();

const data = client.readQuery({query: gql`
  { 
    alert @client
  }
`});
console.log('data:', data);

但是在客户端实例上运行 readQuery 时出现此错误 Missing selection set for object of type Alert returned for query field alert。似乎没有定义Alert。但我已经在typeDefs 中定义了Alert 查询。如果我将查询代码更改为下面我必须指定要在{ message } 中返回的内容,它工作正常。但它似乎没有使用架构。我期望的是,如果它返回架构对象中的所有字段,我不需要指定返回字段。我是否误解了架构?

const data = client.readQuery({query: gql`
  { 
    alert @client {
      message
    }
  }
`});
console.log('data:', data);

如果我必须一一指定返回字段,定义架构有什么意义?

【问题讨论】:

    标签: graphql apollo react-apollo


    【解决方案1】:

    这是 GraphQL 的预期行为。您始终需要在查询中指定您期望的字段。因此,为了接收所有数据,您将字段添加到查询中:

    const data = client.readQuery({query: gql`
      { 
        alert @client {
          message
          type
          duration
        }
      }
    `});
    console.log('data:', data);
    

    GraphQL 规范中有一个open issue

    【讨论】:

    • 是否有快捷方式来选择对象的所有字段?如果我在很多地方都需要这个查询,我不想一一指定。
    • 很遗憾没有。检查问题以获取更多信息
    【解决方案2】:

    您可以使用实体的所有字段定义fragment,然后重用它。 像这样

    fragment AllAlertFields on Alert {
      message
      type
      duration
    }
    

    然后在查询中

    query {
      allAlerts {
        ...AllAlertFields
      }  
    }
    

    更多详情:https://www.apollographql.com/docs/react/data/fragments/

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2020-05-14
      • 2019-11-12
      • 2020-09-20
      • 1970-01-01
      • 2020-01-30
      • 2020-04-03
      • 2018-08-21
      • 2021-09-21
      相关资源
      最近更新 更多