|
| 1 | +--- |
| 2 | +title: Query complexity |
| 3 | +id: version-1.1.1-complexity |
| 4 | +original_id: complexity |
| 5 | +--- |
| 6 | + |
| 7 | +A single GraphQL query can potentially generate a huge workload for a server, like thousands of database operations which can be used to cause DDoS attacks. In order to limit and keep track of what each GraphQL operation can do, `TypeGraphQL` provides the option of integrating with Query Complexity tools like [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity). |
| 8 | + |
| 9 | +This cost analysis-based solution is very promising, since we can define a “cost” per field and then analyze the AST to estimate the total cost of the GraphQL query. Of course all the analysis is handled by `graphql-query-complexity`. |
| 10 | + |
| 11 | +All we must do is define our complexity cost for the fields, mutations or subscriptions in `TypeGraphQL` and implement `graphql-query-complexity` in whatever GraphQL server that is being used. |
| 12 | + |
| 13 | +## How to use |
| 14 | + |
| 15 | +First, we need to pass `complexity` as an option to the decorator on a field, query or mutation. |
| 16 | + |
| 17 | +Example of complexity |
| 18 | + |
| 19 | +```typescript |
| 20 | +@ObjectType() |
| 21 | +class MyObject { |
| 22 | + @Field({ complexity: 2 }) |
| 23 | + publicField: string; |
| 24 | + |
| 25 | + @Field({ complexity: ({ args, childComplexity }) => childComplexity + 1 }) |
| 26 | + complexField: string; |
| 27 | +} |
| 28 | +``` |
| 29 | + |
| 30 | +The `complexity` option may be omitted if the complexity value is 1. |
| 31 | +Complexity can be passed as an option to any `@Field`, `@FieldResolver`, `@Mutation` or `@Subscription` decorator. If both `@FieldResolver` and `@Field` decorators of the same property have complexity defined, then the complexity passed to the field resolver decorator takes precedence. |
| 32 | + |
| 33 | +In the next step, we will integrate `graphql-query-complexity` with the server that expose our GraphQL schema over HTTP. |
| 34 | +You can use it with `express-graphql` like [in the lib examples](https://github.com/slicknode/graphql-query-complexity/blob/b6a000c0984f7391f3b4e886e3df6a7ed1093b07/README.md#usage-with-express-graphql), however we will use Apollo Server like in our other examples: |
| 35 | + |
| 36 | +```typescript |
| 37 | +async function bootstrap() { |
| 38 | + // ...build TypeGraphQL schema as always |
| 39 | + |
| 40 | + // Create GraphQL server |
| 41 | + const server = new ApolloServer({ |
| 42 | + schema, |
| 43 | + // Create a plugin that will allow for query complexity calculation for every request |
| 44 | + plugins: [ |
| 45 | + { |
| 46 | + requestDidStart: () => ({ |
| 47 | + didResolveOperation({ request, document }) { |
| 48 | + /** |
| 49 | + * This provides GraphQL query analysis to be able to react on complex queries to your GraphQL server. |
| 50 | + * This can be used to protect your GraphQL servers against resource exhaustion and DoS attacks. |
| 51 | + * More documentation can be found at https://github.com/ivome/graphql-query-complexity. |
| 52 | + */ |
| 53 | + const complexity = getComplexity({ |
| 54 | + // Our built schema |
| 55 | + schema, |
| 56 | + // To calculate query complexity properly, |
| 57 | + // we have to check only the requested operation |
| 58 | + // not the whole document that may contains multiple operations |
| 59 | + operationName: request.operationName, |
| 60 | + // The GraphQL query document |
| 61 | + query: document, |
| 62 | + // The variables for our GraphQL query |
| 63 | + variables: request.variables, |
| 64 | + // Add any number of estimators. The estimators are invoked in order, the first |
| 65 | + // numeric value that is being returned by an estimator is used as the field complexity. |
| 66 | + // If no estimator returns a value, an exception is raised. |
| 67 | + estimators: [ |
| 68 | + // Using fieldExtensionsEstimator is mandatory to make it work with type-graphql. |
| 69 | + fieldExtensionsEstimator(), |
| 70 | + // Add more estimators here... |
| 71 | + // This will assign each field a complexity of 1 |
| 72 | + // if no other estimator returned a value. |
| 73 | + simpleEstimator({ defaultComplexity: 1 }), |
| 74 | + ], |
| 75 | + }); |
| 76 | + // Here we can react to the calculated complexity, |
| 77 | + // like compare it with max and throw error when the threshold is reached. |
| 78 | + if (complexity > 20) { |
| 79 | + throw new Error( |
| 80 | + `Sorry, too complicated query! ${complexity} is over 20 that is the max allowed complexity.`, |
| 81 | + ); |
| 82 | + } |
| 83 | + // And here we can e.g. subtract the complexity point from hourly API calls limit. |
| 84 | + console.log("Used query complexity points:", complexity); |
| 85 | + }, |
| 86 | + }), |
| 87 | + }, |
| 88 | + ], |
| 89 | + }); |
| 90 | + |
| 91 | + // ...start the server as always |
| 92 | +} |
| 93 | +``` |
| 94 | + |
| 95 | +And it's done! 😉 |
| 96 | + |
| 97 | +For more info about how query complexity is computed, please visit [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity). |
| 98 | + |
| 99 | +## Example |
| 100 | + |
| 101 | +See how this works in the [simple query complexity example](https://github.com/MichalLytek/type-graphql/tree/v1.1.1/examples/query-complexity). |
0 commit comments