在 Apollo 3 中,可以使用 start
和 limit
参数来进行分页,同时还可以使用 fields
参数来指定返回的字段策略。
下面是一个使用代码示例:
const ApolloClient = require('apollo-client');
const { createHttpLink } = require('apollo-link-http');
const { InMemoryCache } = require('apollo-cache-inmemory');
const gql = require('graphql-tag');
// 创建 Apollo Client
const httpLink = createHttpLink({
uri: 'https://api.example.com/graphql', // 替换成实际的 GraphQL API 地址
});
const cache = new InMemoryCache();
const client = new ApolloClient({
link: httpLink,
cache,
});
// 定义查询
const GET_USERS = gql`
query GetUsers($start: Int, $limit: Int, $fields: [String]) {
users(start: $start, limit: $limit, fields: $fields) {
id
name
email
age
}
}
`;
// 发起查询
const start = 0;
const limit = 10;
const fields = ['name', 'email'];
client.query({
query: GET_USERS,
variables: { start, limit, fields },
}).then(result => {
console.log(result.data.users);
}).catch(error => {
console.error(error);
});
上述代码示例中,我们使用 Apollo Client 创建了一个连接到 GraphQL API 的客户端。然后,定义了一个名为 GET_USERS
的查询,其中使用了参数 start
、limit
和 fields
。在查询中,我们使用了这些参数来进行分页和字段策略的控制。
最后,我们使用 client.query
方法发起查询,并传入相应的参数。查询结果会打印到控制台上。
请注意,上述代码示例中的 GraphQL API 地址需要替换成实际的地址,并确保该 API 支持相应的查询和参数。
上一篇:Apollo 3 分页未合并。