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

时间:2019-06-24 04:27:52

标签: graphql apollo react-apollo

我在我的应聘申请人中使用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]
  });
};

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

const client = createClient();

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

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

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

如果必须一一指定返回字段,那么定义架构的重点是什么?

2 个答案:

答案 0 :(得分:0)

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

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

GraphQL规范中有一个open issue

答案 1 :(得分:0)

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

fragment AllAlertFields on Alert {
  message
  type
  duration
}

然后在查询中

query {
  allAlerts {
    ...AllAlertFields
  }  
}

更多详细信息:https://www.apollographql.com/docs/react/data/fragments/

相关问题