67 lines
2.2 KiB
JavaScript
67 lines
2.2 KiB
JavaScript
import { GraphQLError } from '../../error/GraphQLError';
|
|
export function unusedFragMessage(fragName) {
|
|
return "Fragment \"".concat(fragName, "\" is never used.");
|
|
}
|
|
/**
|
|
* No unused fragments
|
|
*
|
|
* A GraphQL document is only valid if all fragment definitions are spread
|
|
* within operations, or spread within other fragments spread within operations.
|
|
*/
|
|
|
|
export function NoUnusedFragments(context) {
|
|
var operationDefs = [];
|
|
var fragmentDefs = [];
|
|
return {
|
|
OperationDefinition: function OperationDefinition(node) {
|
|
operationDefs.push(node);
|
|
return false;
|
|
},
|
|
FragmentDefinition: function FragmentDefinition(node) {
|
|
fragmentDefs.push(node);
|
|
return false;
|
|
},
|
|
Document: {
|
|
leave: function leave() {
|
|
var fragmentNameUsed = Object.create(null);
|
|
|
|
for (var _i = 0, _operationDefs = operationDefs; _i < _operationDefs.length; _i++) {
|
|
var operation = _operationDefs[_i];
|
|
var _iteratorNormalCompletion = true;
|
|
var _didIteratorError = false;
|
|
var _iteratorError = undefined;
|
|
|
|
try {
|
|
for (var _iterator = context.getRecursivelyReferencedFragments(operation)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
|
var fragment = _step.value;
|
|
fragmentNameUsed[fragment.name.value] = true;
|
|
}
|
|
} catch (err) {
|
|
_didIteratorError = true;
|
|
_iteratorError = err;
|
|
} finally {
|
|
try {
|
|
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
_iterator.return();
|
|
}
|
|
} finally {
|
|
if (_didIteratorError) {
|
|
throw _iteratorError;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (var _i2 = 0, _fragmentDefs = fragmentDefs; _i2 < _fragmentDefs.length; _i2++) {
|
|
var fragmentDef = _fragmentDefs[_i2];
|
|
var fragName = fragmentDef.name.value;
|
|
|
|
if (fragmentNameUsed[fragName] !== true) {
|
|
context.reportError(new GraphQLError(unusedFragMessage(fragName), fragmentDef));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
}
|