如何在“react-apollo”应用程序中定义客户端模式?

How to define client side schema in `react-apollo` application?

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

我有以下类型定义:

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

它定义了一个 Query,其中 return 是一个 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 alertAlert 似乎没有定义。但是我已经在 typeDefs 中定义了 Alert 查询。如果我将查询代码更改为必须在 { message } 中指定要 return 的内容,它就可以正常工作。但它似乎没有使用架构。我期望的是,如果 return 是模式对象中的所有字段,我不需要指定 return 字段。我是否误解了架构?

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

如果我必须一一指定 return 字段,定义模式有什么意义?

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

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

GraphQL 规范中有 open issue

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

fragment AllAlertFields on Alert {
  message
  type
  duration
}

然后在一个查询中

query {
  allAlerts {
    ...AllAlertFields
  }  
}

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