1.0.8 • Published 6 years ago
graphql-cost v1.0.8
Essential GraphQL Query Cost Analysis
A simplified version of graphql-cost-analysis
Simple Setup
Init the cost analyzer
import {costAnalysis} from 'graphql-cost'
const validationRules = [
costAnalysis({ maximumCost: 1000 })
]
Configuration
The costAnalysis
function accepts the following options:
Argument | Description | Type | Required |
---|---|---|---|
maximumCost | The maximum allowed cost. Queries above this threshold will be rejected. | Int | yes |
variables | The query variables. This is needed because the variables are not available in the visitor of the graphql-js library. | Object | no |
onComplete(cost) | Callback function to retrieve the determined query cost. It will be invoked whether the query is rejected or not. This can be used for logging or to implement rate limiting (for example, to store the cost by session and define a max cost the user can have in a specific time). | Function | no |
Cost directive
Now that your global configuration is set, you can define the cost calculation for each of your queries, mutations, subscriptions, and fields through a @cost
directive
Arguments
Argument | Description | Type | Required |
---|---|---|---|
multipliers | An array containing names of parameters present in the GraphQL field. Use parameters values to compute the field's cost dynamically. N.B: if the parameter is an array, its multiplier value will be the length of the array. E.g. posts(first: 5, last: 5, list: ["my", "list"]) . The multipliers array could be ["first", "last", "list"] . Then the cost would be complexity * (first + last + list.length ). | Array | no |
childrenMultipliers | Same as multipliers but for the fields of the current object | Array | no |
complexity | The level of complexity to resolve the current field. If the field needs to call an expensive service to resolve itself, then the complexity should be at a high level but if the field is easy to resolve and not an expensive operation, the complexity should be at a low level. | Number | no |
See unit test for examples