-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransforms.js
95 lines (85 loc) · 2.09 KB
/
transforms.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const {
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLNonNull
} = require(`gatsby/graphql`);
const {
visitSchema,
VisitSchemaKind
} = require(`graphql-tools/dist/transforms/visitSchema`);
const {
createResolveType,
fieldMapToFieldConfigMap
} = require(`graphql-tools/dist/stitching/schemaRecreation`);
class NamespaceUnderFieldTransform {
constructor({ typeName, fieldName, paramName, resolver }) {
this.typeName = typeName;
this.fieldName = fieldName;
this.paramName = paramName;
this.resolver = resolver;
}
transformSchema(schema) {
const query = schema.getQueryType();
let newQuery;
const nestedType = new GraphQLObjectType({
name: this.typeName,
fields: () =>
fieldMapToFieldConfigMap(
query.getFields(),
createResolveType(typeName => {
if (typeName === query.name) {
return newQuery;
} else {
return schema.getType(typeName);
}
}),
true
)
});
newQuery = new GraphQLObjectType({
name: query.name,
fields: {
[this.fieldName]: {
type: nestedType,
args: {
[this.paramName]: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (parent, args, context, info) => {
if (this.resolver) {
return this.resolver(parent, args, context, info);
} else {
return {};
}
}
}
}
});
const typeMap = schema.getTypeMap();
const allTypes = Object.keys(typeMap)
.filter(name => name !== query.name)
.map(key => typeMap[key]);
return new GraphQLSchema({
query: newQuery,
types: allTypes
});
}
}
class StripNonQueryTransform {
transformSchema(schema) {
return visitSchema(schema, {
[VisitSchemaKind.MUTATION]() {
return null;
},
[VisitSchemaKind.SUBSCRIPTION]() {
return null;
}
});
}
}
module.exports = {
NamespaceUnderFieldTransform,
StripNonQueryTransform
};