UNPKG

3.36 kBJavaScriptView Raw
1import { GraphQLInputObjectType, GraphQLInterfaceType, GraphQLObjectType, } from 'graphql';
2import { MapperKind } from './Interfaces.js';
3import { mapSchema } from './mapSchema.js';
4export function filterSchema({ schema, typeFilter = () => true, fieldFilter = undefined, rootFieldFilter = undefined, objectFieldFilter = undefined, interfaceFieldFilter = undefined, inputObjectFieldFilter = undefined, argumentFilter = undefined, }) {
5 const filteredSchema = mapSchema(schema, {
6 [MapperKind.QUERY]: (type) => filterRootFields(type, 'Query', rootFieldFilter, argumentFilter),
7 [MapperKind.MUTATION]: (type) => filterRootFields(type, 'Mutation', rootFieldFilter, argumentFilter),
8 [MapperKind.SUBSCRIPTION]: (type) => filterRootFields(type, 'Subscription', rootFieldFilter, argumentFilter),
9 [MapperKind.OBJECT_TYPE]: (type) => typeFilter(type.name, type)
10 ? filterElementFields(GraphQLObjectType, type, objectFieldFilter || fieldFilter, argumentFilter)
11 : null,
12 [MapperKind.INTERFACE_TYPE]: (type) => typeFilter(type.name, type)
13 ? filterElementFields(GraphQLInterfaceType, type, interfaceFieldFilter || fieldFilter, argumentFilter)
14 : null,
15 [MapperKind.INPUT_OBJECT_TYPE]: (type) => typeFilter(type.name, type)
16 ? filterElementFields(GraphQLInputObjectType, type, inputObjectFieldFilter || fieldFilter)
17 : null,
18 [MapperKind.UNION_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),
19 [MapperKind.ENUM_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),
20 [MapperKind.SCALAR_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),
21 });
22 return filteredSchema;
23}
24function filterRootFields(type, operation, rootFieldFilter, argumentFilter) {
25 if (rootFieldFilter || argumentFilter) {
26 const config = type.toConfig();
27 for (const fieldName in config.fields) {
28 const field = config.fields[fieldName];
29 if (rootFieldFilter && !rootFieldFilter(operation, fieldName, config.fields[fieldName])) {
30 delete config.fields[fieldName];
31 }
32 else if (argumentFilter && field.args) {
33 for (const argName in field.args) {
34 if (!argumentFilter(operation, fieldName, argName, field.args[argName])) {
35 delete field.args[argName];
36 }
37 }
38 }
39 }
40 return new GraphQLObjectType(config);
41 }
42 return type;
43}
44function filterElementFields(ElementConstructor, type, fieldFilter, argumentFilter) {
45 if (fieldFilter || argumentFilter) {
46 const config = type.toConfig();
47 for (const fieldName in config.fields) {
48 const field = config.fields[fieldName];
49 if (fieldFilter && !fieldFilter(type.name, fieldName, config.fields[fieldName])) {
50 delete config.fields[fieldName];
51 }
52 else if (argumentFilter && 'args' in field) {
53 for (const argName in field.args) {
54 if (!argumentFilter(type.name, fieldName, argName, field.args[argName])) {
55 delete field.args[argName];
56 }
57 }
58 }
59 }
60 return new ElementConstructor(config);
61 }
62}