Complexity

Warning This chapter applies only to the code first approach.

Query complexity allows you to define how complex certain fields are, and to restrict queries with a maximum complexity. The idea is to define how complex each field is by using a simple number. A common default is to give each field a complexity of 1. In addition, the complexity calculation of a GraphQL query can be customized with so-called complexity estimators. A complexity estimator is a simple function that calculates the complexity for a field. You can add any number of complexity estimators to the rule, which are then executed one after another. The first estimator that returns a numeric complexity value determines the complexity for that field.

The @nestjs/graphql package integrates very well with tools like graphql-query-complexity that provides a cost analysis-based solution. With this library, you can reject queries to your GraphQL server that are deemed too costly to execute.

Installation

To begin using it, we first install the required dependency.

  1. $ npm install --save graphql-query-complexity

Getting started

Once the installation process is complete, we can define the ComplexityPlugin class:

  1. import { GraphQLSchemaHost, Plugin } from '@nestjs/graphql';
  2. import {
  3. ApolloServerPlugin,
  4. GraphQLRequestListener,
  5. } from 'apollo-server-plugin-base';
  6. import { GraphQLError } from 'graphql';
  7. import {
  8. fieldExtensionsEstimator,
  9. getComplexity,
  10. simpleEstimator,
  11. } from 'graphql-query-complexity';
  12. @Plugin()
  13. export class ComplexityPlugin implements ApolloServerPlugin {
  14. constructor(private gqlSchemaHost: GraphQLSchemaHost) {}
  15. requestDidStart(): GraphQLRequestListener {
  16. const { schema } = this.gqlSchemaHost;
  17. return {
  18. didResolveOperation({ request, document }) {
  19. const complexity = getComplexity({
  20. schema,
  21. operationName: request.operationName,
  22. query: document,
  23. variables: request.variables,
  24. estimators: [
  25. fieldExtensionsEstimator(),
  26. simpleEstimator({ defaultComplexity: 1 }),
  27. ],
  28. });
  29. if (complexity >= 20) {
  30. throw new GraphQLError(
  31. `Query is too complex: ${complexity}. Maximum allowed complexity: 20`,
  32. );
  33. }
  34. console.log('Query Complexity:', complexity);
  35. },
  36. };
  37. }
  38. }

For demonstration purposes, we specified the maximum allowed complexity as 20. In the example above, we used 2 estimators, the simpleEstimator and the fieldExtensionsEstimator.

  • simpleEstimator: the simple estimator returns a fixed complexity for each field
  • fieldExtensionsEstimator: the field extensions estimator extracts the complexity value for each field of your schema

Hint Remember to add this class to the providers array in any module.

Field-level complexity

With this plugin in place, we can now define the complexity for any field by specifying the complexity property in the options object passed into the @Field() decorator, as follows:

  1. @Field({ complexity: 3 })
  2. title: string;

Alternatively, you can define the estimator function:

  1. @Field({ complexity: (options: ComplexityEstimatorArgs) => ... })
  2. title: string;