graphql-shield
Version:
GraphQL Server permissions as another layer of abstraction!
62 lines (61 loc) • 2.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareFragmentReplacements = void 0;
// copied from https://github.com/dimatill/graphql-middleware/blob/1c33515adb45da9a7358e03d56cd5edbf6918649/src/fragments.ts
const graphql_1 = require("graphql");
function parseFragmentToInlineFragment(definitions) {
if (definitions.trim().startsWith('fragment')) {
const document = (0, graphql_1.parse)(definitions);
for (const definition of document.definitions) {
if (definition.kind === graphql_1.Kind.FRAGMENT_DEFINITION) {
return {
kind: graphql_1.Kind.INLINE_FRAGMENT,
typeCondition: definition.typeCondition,
selectionSet: definition.selectionSet,
};
}
}
}
const query = (0, graphql_1.parse)(`{${definitions}}`).definitions[0];
for (const selection of query.selectionSet.selections) {
if (selection.kind === graphql_1.Kind.INLINE_FRAGMENT) {
return selection;
}
}
throw new Error('Could not parse fragment');
}
function prepareFragmentReplacements(fragmentReplacements) {
return fragmentReplacements
.filter((fragment) => Boolean(fragment))
.map((fragmentReplacement) => {
const fragment = parseFragmentToInlineFragment(fragmentReplacement.fragment);
const newSelections = fragment.selectionSet.selections.filter((node) => {
switch (node.kind) {
case graphql_1.Kind.FIELD: {
return node.name.value !== fragmentReplacement.field;
}
default: {
return true;
}
}
});
if (newSelections.length === 0) {
return null;
}
const newFragment = {
...fragment,
selectionSet: {
kind: fragment.selectionSet.kind,
loc: fragment.selectionSet.loc,
selections: newSelections,
},
};
const parsedFragment = (0, graphql_1.print)(newFragment);
return {
field: fragmentReplacement.field,
fragment: parsedFragment,
};
})
.filter((fr) => fr !== null);
}
exports.prepareFragmentReplacements = prepareFragmentReplacements;