|
1 |
| -# Typescript Library Template |
| 1 | +# Graphql Query Complexity Apollo Plugin |
2 | 2 |
|
3 |
| -[](https://github.com/reconbot/typescript-library-template/actions/workflows/test.yml) |
| 3 | +[](https://github.com/reconbot/graphql-query-complexity-apollo-plugin/actions/workflows/test.yml) |
4 | 4 |
|
5 |
| -This is an example project for shipping typescript using the rules layed out by [@southpolesteve](https://twitter.com/southpolesteve) in his ["Shipping Typescript to NPM"](https://speakerdeck.com/southpolesteve/shipping-typescript-to-npm?slide=10) talk that he gave at NYC typescript. |
| 5 | +This is a plugin for Apollo Server 3 that throws if a query is too complex. |
6 | 6 |
|
7 |
| -It gives you a library in UMD and ESM that's rolled up with rollup and includes rolled up types. It makes browser users, node users and me very happy. |
| 7 | +## Example |
8 | 8 |
|
9 |
| -Also includes eslint, mocha, semantic-release and github actions. Now updated to include the exports directive in the package.json. |
| 9 | +```ts |
| 10 | +import { ApolloServer } from 'apollo-server-lambda' |
| 11 | +import { schema } from './schema' |
| 12 | +import { context } from './context' |
| 13 | +import { SystemConfigOptions } from '../lib/SystemConfig' |
| 14 | +import { fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity' |
| 15 | +import { createComplexityPlugin } from './createComplexityPlugin' |
10 | 16 |
|
11 |
| -## Guide |
| 17 | +return new ApolloServer({ |
| 18 | + schema, |
| 19 | + context, |
| 20 | + plugins: [ |
| 21 | + createComplexityPlugin({ |
| 22 | + schema, |
| 23 | + estimators: [ |
| 24 | + fieldExtensionsEstimator(), |
| 25 | + simpleEstimator({ defaultComplexity: 1 }), |
| 26 | + ], |
| 27 | + maximumComplexity: 1000, |
| 28 | + onComplete: (complexity) => { |
| 29 | + console.log('Query Complexity:', complexity) |
| 30 | + }, |
| 31 | + }), |
| 32 | + ], |
| 33 | +}) |
| 34 | +``` |
12 | 35 |
|
13 |
| -- Set the repo secret `NPM_TOKEN` before your first push so that you can publish to npm. |
14 |
| -- Change all references in package.json to your own project name |
15 |
| -- If you want external dependencies, add them to the `external` section in the `rollup.config.js` otherwise they will be bundled in the library. |
| 36 | +## API |
| 37 | + |
| 38 | +```ts |
| 39 | +export const createComplexityPlugin: ({ schema, maximumComplexity, estimators, onComplete, createError }: { |
| 40 | + schema: GraphQLSchema |
| 41 | + maximumComplexity: number |
| 42 | + estimators: Array<ComplexityEstimator> |
| 43 | + onComplete?: ((complexity: number) => Promise<void> | void) |
| 44 | + createError?: ((max: number, actual: number) => Promise<GraphQLError> | GraphQLError) |
| 45 | +}) => PluginDefinition |
| 46 | +``` |
| 47 | +
|
| 48 | +- `createError` should return an error to be thrown if the actual complexity is more than the maximum complexity. |
0 commit comments