UNPKG

@graphql-eslint/eslint-plugin

Version:

GraphQL plugin for ESLint

68 lines (67 loc) • 2.03 kB
import { Kind } from "graphql"; function checkDepthLimit(document, options) { const fragments = getDefinitionsByName( document.definitions, Kind.FRAGMENT_DEFINITION ); const operations = getDefinitionsByName( document.definitions, Kind.OPERATION_DEFINITION ); for (const [operationName, operation] of Object.entries(operations)) { determineDepth(operation, fragments, 0, operationName, options); } } function getDefinitionsByName(definitions, kind) { const map = {}; for (const definition of definitions) { if (definition.kind === kind) { map[definition.name?.value ?? ""] = definition; } } return map; } function determineDepth(node, fragments, depthSoFar, operationName, options) { if (depthSoFar > options.maxDepth) { options.onDepthExceeded(node, operationName); return depthSoFar; } switch (node.kind) { case Kind.FIELD: { const shouldIgnore = node.name.value.startsWith("__") || isIgnored(node.name.value, options.ignore); if (shouldIgnore || !node.selectionSet) { return 0; } return 1 + Math.max( ...node.selectionSet.selections.map( (selection) => determineDepth(selection, fragments, depthSoFar + 1, operationName, options) ) ); } case Kind.FRAGMENT_SPREAD: { const fragment = fragments[node.name.value]; if (!fragment) { throw new Error(`Unknown fragment "${node.name.value}"`); } return determineDepth(fragment, fragments, depthSoFar, operationName, options); } case Kind.INLINE_FRAGMENT: case Kind.FRAGMENT_DEFINITION: case Kind.OPERATION_DEFINITION: return Math.max( ...node.selectionSet.selections.map( (selection) => determineDepth(selection, fragments, depthSoFar, operationName, options) ) ); } } function isIgnored(fieldName, ignore) { return ignore.some( (rule) => typeof rule === "function" ? rule(fieldName) : fieldName.match(rule) ); } export { checkDepthLimit };