GraphQL API 的高级查询
🌐 Advanced queries for the GraphQL API
Strapi 的 GraphQL API 可以自动解析许多查询,但复杂的数据访问可能需要更深入的关系获取或链接解析器。本简短指南解释了如何处理这些高级场景。
🌐 Strapi's GraphQL API resolves many queries automatically, but complex data access can require deeper relation fetching or chaining resolvers. The present short guide explains how to handle such advanced scenarios.
如需更多信息,请参阅 GraphQL 自定义 文档。
🌐 For additional information, please refer to the GraphQL customization documentation.
多层查询
🌐 Multi-level queries
使用嵌 套选择集来获取多层级关系,如下例所示:
🌐 Use nested selection sets to fetch relations several levels deep, as in the following example:
{
restaurants {
documentId
name
categories {
documentId
name
parent {
documentId
name
}
}
}
}
GraphQL 插件会自动解析嵌套关系。如果你需要在特定级别应用自定义逻辑,请为该字段创建自定义解析器。
🌐 The GraphQL plugin automatically resolves nested relations. If you need to apply custom logic at a specific level, create a custom resolver for that field.
解析器链
🌐 Resolver chains
自定义解析器可以调用其他解析器以重用现有逻辑。一种常见的模式是在父解析器中解析权限或上下文数据,并将其传递给子解析器,如以下示例所示:
🌐 Custom resolvers can call other resolvers to reuse existing logic. A common pattern is to resolve permissions or context data in a parent resolver and pass it down to child resolvers, as in the following example:
export default {
Query: {
restaurants: async (parent, args, ctx) => {
const documents = await strapi.documents('api::restaurant.restaurant').findMany(args);
return documents.map(doc => ctx.request.graphql.resolve('Restaurant', doc));
},
},
};
在这个示例中,父解析器使用 Document Service API 获取餐馆,然后委托给插件提供的生成的 Restaurant 解析器,因此默认行为(例如字段选择)仍然适用。
🌐 In this example the parent resolver fetches restaurants using the Document Service API, then delegates to the generated Restaurant resolver provided by the plugin so default behavior such as field selection still applies.
聚合下钻
🌐 Aggregation drilldowns
Relay-style 连接会显示一个 aggregate 字段。你可以使用它来展示高级指标,同时让用户深入查看特定的组。将 groupBy 与分页变量结合使用以保持响应体积小:
query RestaurantsByCity($first: Int, $after: String) {
restaurants_connection(pagination: { limit: $first, start: $after }) {
aggregate {
groupBy {
city {
key
connection(pagination: { limit: 5 }) {
aggregate {
count
}
nodes {
documentId
name
}
}
}
}
}
}
}
当用户选择一个组时,使用查询变量来调整嵌套分页。Strapi 在服务器上运行聚合,这就是为什么客户端只下载所需的摘要行:即使在大数据集中,这也能保持仪表板的响应速度。
🌐 Use query variables to adjust the nested pagination when a user selects a group. Strapi runs the aggregation on the server, which is why the client only downloads the summary rows it needs: this keeps dashboards responsive even with large data sets.