@graphql-inspector/core
Version:
Tooling for GraphQL. Compare GraphQL Schemas, check documents, find breaking changes, find similar types.
36 lines (35 loc) • 1.53 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateDirectiveCount = validateDirectiveCount;
exports.countDirectives = countDirectives;
const graphql_1 = require("graphql");
function validateDirectiveCount({ source, doc, maxDirectiveCount, fragmentGraph, }) {
const getFragmentByFragmentName = (fragmentName) => fragmentGraph.getNodeData(fragmentName);
for (const definition of doc.definitions) {
if (definition.kind !== graphql_1.Kind.OPERATION_DEFINITION) {
continue;
}
const directiveCount = countDirectives(definition, getFragmentByFragmentName);
if (directiveCount > maxDirectiveCount) {
return new graphql_1.GraphQLError(`Too many directives (${directiveCount}). Maximum allowed is ${maxDirectiveCount}`, [definition], source, definition.loc?.start ? [definition.loc.start] : undefined);
}
}
}
function countDirectives(node, getFragmentByName) {
let directives = 0;
if (node.directives) {
directives += node.directives.length;
}
if ('selectionSet' in node && node.selectionSet) {
for (const child of node.selectionSet.selections) {
directives += countDirectives(child, getFragmentByName);
}
}
if (node.kind === graphql_1.Kind.FRAGMENT_SPREAD) {
const fragment = getFragmentByName(node.name.value);
if (fragment) {
directives += countDirectives(fragment, getFragmentByName);
}
}
return directives;
}
;