slicknode / graphql-query-complexity

GraphQL query complexity analysis and validation for graphql-js
MIT License
726 stars 41 forks source link

How to implement with Apollo server v3 #81

Open daniel-keller opened 1 year ago

daniel-keller commented 1 year ago

I spent several hours finding the best way to implement graphql-query-complexity with Apollo server v3 (server and serverless) and I just wanted to post the answer in case anyone else needs it.

The trouble I ran into is that apollo server doesn't give its validationRules access to the request object so calculating query complexity based on request parameters is not possible. In apollo validationRules are not guaranteed to run on every request.

The solution is to use the plugin api's didResolveOperation hook to manually trigger a complexity calculation further along the request pipeline as explained here.

If you are using express (apollo-server-express or apollo-server-lambda or apollo-server-cloud-functions) you could probably do this as express middleware as well.

Feel free to close this Issue.

EDIT: You will need to modify the code example to work with the latest version of graphql-query-complexity (fieldConfigEstimator is deprecated). If you are using Apollo and building your schema using gql() you may also need to convert your schema into a GraphQLSchema. Graphql includes a utility to do this import { buildASTSchema } from 'graphql';.

shadowbrush commented 3 months ago

Thank you, @daniel-keller, that was helpful a few years later. To add to this: use fieldExtensionsEstimator as replacement for fieldConfigEstimator. Works great.