-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathastToSchema.ts
205 lines (183 loc) · 5.53 KB
/
astToSchema.ts
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import {
SchemaComposer,
ObjectTypeComposer,
upperFirst,
ObjectTypeComposerFieldConfig,
isOutputTypeDefinitionString,
isWrappedTypeNameString,
inspect,
} from 'graphql-compose';
import { AstRootNode, AstRootTypeNode, AstDirNode, AstFileNode } from './directoryToAst';
import dedent from 'dedent';
import { GraphQLObjectType } from 'graphql';
export interface AstToSchemaOptions {
/**
* Pass here already existed SchemaComposer instance
* which already contains some types (eg with custom Scalars).
*
* Or new SchemaComposer instance will be created.
*/
schemaComposer?: SchemaComposer<any>;
prefix?: string;
suffix?: string;
}
/**
* Transform AST to GraphQL Schema.
*
* @example
* // Scan some directory for getting Schema entrypoints as AST nodes.
* const ast = directoryToAst(module);
*
* // [Optional] Combining severals ast into source
* // Useful if some sub-schemas are delivered via packages
* // or created n separate directories.
* const newAST = astMerge(ast, ast1, ast2, ...);
*
* // [Optional] Some `ast` modifications
* // Useful for writing some middlewares
* // which transform FieldConfigs entrypoints.
* astVisitor(newAST, visitorFns);
*
* // Create SchemaComposer instance with all populated types & fields
* // It provides declarative programmatic access to modify you schema
* const schemaComposer = astToSchema(newAST, opts);
*
* // Create GraphQLSchema instance which is ready for runtime.
* const schema = schemaComposer.buildSchema();;
*/
export function astToSchema<TContext = any>(
ast: AstRootNode,
opts: AstToSchemaOptions = {}
): SchemaComposer<TContext> {
let sc: SchemaComposer<any>;
if (opts?.schemaComposer) {
if (!opts.schemaComposer) {
throw new Error(dedent`
Provided option 'schemaComposer' should be an instance of SchemaComposer class from 'graphql-compose' package.
Received:
${inspect(opts.schemaComposer)}
`);
}
sc = opts.schemaComposer;
} else {
sc = new SchemaComposer();
}
if (ast.children.query) populateRoot(sc, 'Query', ast.children.query, opts);
if (ast.children.mutation) populateRoot(sc, 'Mutation', ast.children.mutation, opts);
if (ast.children.subscription) populateRoot(sc, 'Subscription', ast.children.subscription, opts);
return sc;
}
function populateRoot(
sc: SchemaComposer<any>,
rootName: 'Query' | 'Mutation' | 'Subscription',
astRootNode: AstRootTypeNode,
opts?: AstToSchemaOptions
) {
const tc = sc[rootName];
Object.keys(astRootNode.children).forEach((key) => {
createFields(sc, astRootNode.children[key], tc, rootName, opts || {});
});
}
export function createFields(
sc: SchemaComposer<any>,
ast: AstDirNode | AstFileNode | void,
parent: ObjectTypeComposer,
pathPrefix: string,
opts: AstToSchemaOptions = {}
): void {
if (!ast) return;
const name = ast.name;
if (!/^[._a-zA-Z0-9]+$/.test(name)) {
throw new Error(
`You provide incorrect ${
ast.kind === 'file' ? 'file' : 'directory'
} name '${name}', it should meet RegExp(/^[._a-zA-Z0-9]+$/) for '${ast.absPath}'`
);
}
if (ast.kind === 'file') {
parent.addNestedFields({
[name]: ast.fieldConfig,
});
return;
}
if (ast.kind === 'dir') {
const typename = getTypename(ast, pathPrefix, opts);
let fc: ObjectTypeComposerFieldConfig<any, any>;
if (ast.namespaceConfig) {
fc = prepareNamespaceFieldConfig(sc, ast.namespaceConfig, typename);
} else {
fc = { type: sc.createObjectTC(typename) };
}
parent.addNestedFields({
[name]: {
resolve: (source) => source,
...fc,
},
});
const pathPrefixForChild = getTypename(ast, pathPrefix, {});
Object.keys(ast.children).forEach((key) => {
createFields(sc, ast.children[key], fc.type as any, pathPrefixForChild, opts);
});
}
}
function getTypename(
ast: AstDirNode | AstFileNode,
pathPrefix: string,
opts: AstToSchemaOptions
): string {
const name = ast.name;
let typename = pathPrefix;
if (name.indexOf('.') !== -1) {
const namesArray = name.split('.');
if (namesArray.some((n) => !n)) {
throw new Error(
`Field name '${ast.name}' contains dots in the wrong place for '${ast.absPath}'!`
);
}
typename += namesArray.reduce((prev, current) => {
return prev + upperFirst(current);
}, '');
} else {
typename += upperFirst(name);
}
if (opts.prefix) typename = `${opts.prefix}${typename}`;
if (opts.suffix) typename += opts.suffix;
return typename;
}
function prepareNamespaceFieldConfig(
sc: SchemaComposer<any>,
ast: AstFileNode,
typename: string
): ObjectTypeComposerFieldConfig<any, any> {
const fc = ast.fieldConfig as any;
if (!fc.type) {
fc.type = sc.createObjectTC(typename);
} else {
if (typeof fc.type === 'string') {
if (!isOutputTypeDefinitionString(fc.type) && !isWrappedTypeNameString(fc.type)) {
throw new Error(dedent`
You provide incorrect output type definition:
${fc.type}
It must be valid TypeName or output type SDL definition:
Eg.
type Payload { me: String }
OR
Payload
`);
}
} else if (
!(fc.type instanceof ObjectTypeComposer) &&
!(fc.type instanceof GraphQLObjectType)
) {
throw new Error(dedent`
You provide some strange value as 'type':
${inspect(fc.type)}
`);
}
fc.type = sc.createObjectTC(fc.type);
}
if (!fc.resolve) {
fc.resolve = () => ({});
}
return fc;
}