Analyze and limit the cost of GraphQL queries using configurable field costs
npm install graphql-cost-guardian graphqlimport analyzeCost from 'graphql-cost-guardian';
const result = analyzeCost(`
query {
users {
name
posts {
title
comments {
body
}
}
}
}
`, {
fieldCosts: {'Query.users': 10},
maxCost: 100,
maxDepth: 5,
});
console.log(result.cost);
// => 14
console.log(result.depth);
// => 4import {createCostMiddleware} from 'graphql-cost-guardian';
const analyze = createCostMiddleware({
maxCost: 500,
maxDepth: 10,
defaultCost: 1,
listCostFactor: 10,
});
// Use in your GraphQL server middleware
const result = analyze(incomingQuery);Analyze the cost of a GraphQL query.
Type: string | DocumentNode
A GraphQL query string or a parsed DocumentNode from graphql. Both analyzeCost and the function returned by createCostMiddleware accept either form.
Type: object
Cost values and multipliers must be finite, non-negative numbers. Limits must be non-negative numbers; Infinity means unbounded. Invalid numeric options throw TypeError.
Named fragments are counted at every reachable spread. Fragment wrappers do not add field nesting depth, and unused fragments are ignored.
Type: Record<string, number>
Default: {}
Mapping of TypeName.fieldName to custom cost values.
Type: number
Default: 1
Default cost per field when not specified in fieldCosts.
Type: number
Default: 1
Multiplier applied per nesting depth level.
Type: number
Default: 10
Assumed list size multiplier for fields with list-related arguments (first, last, limit).
Type: number
Maximum allowed cost. Throws CostExceededError when exceeded.
Type: number
Maximum allowed query depth. Throws DepthExceededError when exceeded.
Type: {cost: number, depth: number, fields: Map<string, number>}
Returns a function (query) => CostAnalysis with the given options baked in.
Thrown when query cost exceeds maxCost. Has cost and maxCost properties.
Thrown when query depth exceeds maxDepth. Has depth and maxDepth properties.
- graphql — The JavaScript reference implementation for GraphQL
MIT