@@ -104,32 +104,6 @@ type ComplexityEstimatorArgs = {
104104type ComplexityEstimator = (options : ComplexityEstimatorArgs ) => number | void ;
105105```
106106
107- ## Calculate query complexity
108- ``` javascript
109- import { calculateComplexity , simpleEstimator } from " graphql-query-complexity/dist/QueryComplexity" ;
110- import { parse } from ' graphql' ;
111-
112- // In a resolver the schema can be retrieved from the info argument.
113- const schema = undefined ;
114- const query = parse (`
115- query {
116- some_value
117- some_list(count: 10) {
118- some_child_value
119- }
120- }
121- ` );
122-
123- const complexity = calculateComplexity ({
124- estimators: [
125- simpleEstimator ({defaultComplexity: 1 })
126- ],
127- schema,
128- query
129- });
130-
131- console .log (complexity); // Output: 3
132- ```
133107
134108## Usage with express-graphql
135109
@@ -153,6 +127,43 @@ app.use('/api', graphqlHTTP(async (request, response, {variables}) => ({
153127})));
154128```
155129
130+ ## Calculate query complexity
131+
132+ If you want to calculate the complexity of a GraphQL query outside of the validation phase, for example to
133+ return the complexity value in a resolver, you can calculate the complexity via ` getComplexity ` :
134+
135+ ``` javascript
136+ import { getComplexity , simpleEstimator } from ' graphql-query-complexity' ;
137+ import { parse } from ' graphql' ;
138+
139+ // Import your schema or get it form the info object in your resolver
140+ import schema from ' ./schema' ;
141+
142+ // You can also use gql template tag to get the parsed query
143+ const query = parse (`
144+ query Q($count: Int) {
145+ some_value
146+ some_list(count: $count) {
147+ some_child_value
148+ }
149+ }
150+ ` );
151+
152+ const complexity = getComplexity ({
153+ estimators: [
154+ simpleEstimator ({defaultComplexity: 1 })
155+ ],
156+ schema,
157+ query,
158+ variables: {
159+ count: 10 ,
160+ },
161+ });
162+
163+ console .log (complexity); // Output: 3
164+ ```
165+
166+
156167## Prior Art
157168
158169This project is inspired by the following prior projects:
0 commit comments