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