Query complexity validation for GraphQL.js.
Usage
; const ComplexityLimitRule = ;// Then use this rule with validate() or other validation APIs.
For example, with express-graphql
or Apollo Server, pass the complexity limit rule to validationRules
.
const graphqlMiddleware = ; const apolloServer = schema validationRules: ;
You can provide a configuration object with custom global costs for scalars and objects as scalarCost
and objectCost
respectively, and a custom cost factor for lists as listFactor
.
const ComplexityLimitRule = ;
You can also set custom costs and cost factors as field definition extensions with the getCost
and getCostFactor
callbacks.
const expensiveField = type: ExpensiveItem extensions: 50 ; const expensiveList = type: MyItem extensions: 100 ;
You can also define these via field directives in the SDL.
directive @cost(value: Int) on FIELD_DEFINITIONdirective @costFactor(value: Int) on FIELD_DEFINITION type CustomCostItem { expensiveField: ExpensiveItem @cost(value: 50) expensiveList: [MyItem] @costFactor(value: 100)}
The configuration object also supports an onCost
callback for logging query costs and a formatErrorMessage
callback for customizing error messages. onCost
will be called for every query with its cost. formatErrorMessage
will be called with the cost whenever a query exceeds the complexity limit, and should return a string containing the error message.
const ComplexityLimitRule = ;
The configuration object also supports a createError
callback for creating a custom GraphQLError
. createError
will be called with the cost and the document node whenever an error occurs. formatErrorMessage
will be ignored when createError
is specified.
const ComplexityLimitRule = ;
By default, the validation rule applies a custom, lower cost factor for lists of introspection types, to prevent introspection queries from having unreasonably high costs. You can adjust this by setting introspectionListFactor
on the configuration object.
const ComplexityLimitRule = ;