复杂度
警告
本章仅适用于代码优先方式。
查询复杂度(query complexity)让你可以定义某些字段有多复杂,并用 最大复杂度 来限制查询。其思路是把每个字段的复杂度表示为一个数字。常见的默认做法是给每个字段的复杂度设为 1。你也可以用复杂度估算器(complexity estimator)自定义 GraphQL 查询复杂度的计算方式。复杂度估算器是一个计算字段复杂度的函数。你可以向规则中添加任意数量的估算器,它们会依次运行。第一个返回数值的估算器决定该字段的复杂度。
@nestjs/graphql 包与 graphql-query-complexity 这类工具集成,后者提供了一种基于代价分析的方案。借助这个库,你可以拒绝执行代价过高的查询。
安装
首先,安装所需的依赖:
$ npm install --save graphql-query-complexity开始使用
安装完成后,定义 ComplexityPlugin 类:
import { GraphQLSchemaHost } from '@nestjs/graphql';
import { Plugin } from '@nestjs/apollo';
import {
ApolloServerPlugin,
BaseContext,
GraphQLRequestListener,
} from '@apollo/server';
import { GraphQLError } from 'graphql';
import {
fieldExtensionsEstimator,
getComplexity,
simpleEstimator,
} from 'graphql-query-complexity';
@Plugin()
export class ComplexityPlugin implements ApolloServerPlugin {
constructor(private gqlSchemaHost: GraphQLSchemaHost) {}
async requestDidStart(): Promise<GraphQLRequestListener<BaseContext>> {
const maxComplexity = 20;
const { schema } = this.gqlSchemaHost;
return {
async didResolveOperation({ request, document }) {
const complexity = getComplexity({
schema,
operationName: request.operationName,
query: document,
variables: request.variables,
estimators: [
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
],
});
if (complexity > maxComplexity) {
throw new GraphQLError(
`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`,
);
}
console.log('Query Complexity:', complexity);
},
};
}
}为演示起见,最大允许复杂度设为 20。上面的示例使用了两个估算器:fieldExtensionsEstimator 和 simpleEstimator:
fieldExtensionsEstimator:提取为你 schema 中每个字段定义的复杂度值(通过字段的extensions)simpleEstimator:为每个字段返回固定的复杂度(用作未定义复杂度字段的兜底)
提示
记得把这个类加入某个模块的 providers 数组。
字段级复杂度
有了这个插件,你可以在传给 @Field() 装饰器的选项对象中指定 complexity 属性,从而定义任意字段的复杂度:
@Field({ complexity: 3 })
title: string;或者,你也可以定义一个估算器函数:
@Field({ complexity: (options: ComplexityEstimatorArgs) => ... })
title: string;查询/变更级复杂度
@Query() 和 @Mutation() 装饰器的选项对象也接受 complexity 属性:
@Query(() => [Item], {
complexity: (options: ComplexityEstimatorArgs) =>
options.args.count * options.childComplexity,
})
items(@Args('count') count: number) {
return this.itemsService.getItems({ count });
}