forked from aws/amazon-neptune-for-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschemaModelValidator.js
More file actions
373 lines (307 loc) · 12.3 KB
/
schemaModelValidator.js
File metadata and controls
373 lines (307 loc) · 12.3 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://www.apache.org/licenses/LICENSE-2.0
or in the "license" file accompanying this file. This file is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License.
*/
import { schemaStringify } from './schemaParser.js';
import { GraphQLID, print } from 'graphql';
import {gql} from 'graphql-tag'
import { loggerInfo, yellow } from "./logger.js";
let quiet = false;
const typesToAdd = [];
const queriesToAdd = [];
const mutationsToAdd = [];
function lowercaseFirstCharacter(inputString) {
if (inputString.length === 0) {
return inputString;
}
const firstChar = inputString.charAt(0);
const restOfString = inputString.slice(1);
const lowercasedFirstChar = firstChar.toLowerCase();
return lowercasedFirstChar + restOfString;
}
function isGraphDBDirectives(schemaModel) {
let r = false;
schemaModel.definitions.forEach(def => {
if (def.kind == 'ObjectTypeDefinition') {
def.fields.forEach(field => {
if (field.directives) {
field.directives.forEach(directive => {
if (directive.name.value == 'cypher') {
r = true;
}
if (directive.name.value == 'graphQuery') {
r = true;
}
if (directive.name.value == 'relationship') {
r = true;
}
});
}
});
}
});
return r;
}
function addRelationshipDirective(field, type, direction) {
field.directives.push({
kind: 'Directive',
name: {
kind: 'Name',
value: 'relationship'
},
arguments: [
{
kind: 'Argument',
name: {
kind: 'Name',
value: 'type'
},
value: {
kind: 'StringValue',
value: type,
block: false
}
},
{
kind: 'Argument',
name: {
kind: 'Name',
value: 'direction'
},
value: {
kind: 'EnumValue',
value: direction
}
}
]
});
}
function injectChanges(schemaModel) {
let r = '';
let stringModel = schemaStringify(schemaModel, true);
stringModel += '\n';
typesToAdd.forEach(type => {
stringModel += '\n' + type + '\n';
});
if (!stringModel.includes('type Query {'))
stringModel += '\ntype Query {\n}\n';
if (!stringModel.includes('type Mutation {'))
stringModel += '\ntype Mutation {\n}\n';
if (!stringModel.includes('schema {'))
stringModel += '\nschema {\n query: Query\n mutation: Mutation\n}\n';
const lines = stringModel.split('\n');
lines.forEach(line => {
r += line + '\n';
if (line.includes('type Query {')) {
queriesToAdd.forEach(query => {
r += " " + query;
});
}
if (line.includes('type Mutation {')) {
mutationsToAdd.forEach(mutation => {
r += " " + mutation;
});
}
});
return gql(r);
}
function addNode(def) {
let name = def.name.value;
const idField = getIdField(def);
// Create Input type
const createFields = [];
for (const field of def.fields) {
if (isScalar(nullable(field.type))) {
if (field.type.kind === 'NonNullType' && field.type.type.name.value === GraphQLID.name) {
// make ID nullable by unwrapping the NonNullType from the field
const idFieldCopy = JSON.parse(JSON.stringify(field));
idFieldCopy.type = idFieldCopy.type.type;
createFields.push(idFieldCopy);
} else {
createFields.push(field);
}
}
}
typesToAdd.push(`input ${name}CreateInput {\n${print(createFields)}\n}`);
// Update Input type
const updateFields = [];
for (const field of def.fields) {
if (isScalar(nullable(field.type))) {
if (field.type.kind === 'NonNullType') {
// make non-nullable nullable by unwrapping the NonNullType from the field
const fieldCopy = JSON.parse(JSON.stringify(field));
fieldCopy.type = fieldCopy.type.type;
updateFields.push(fieldCopy);
} else {
updateFields.push(field);
}
}
}
typesToAdd.push(`input ${name}UpdateInput {\n${print(updateFields)}\n}`);
// Create query
queriesToAdd.push(`getNode${name}(filter: ${name}Input, options: Options): ${name}\n`);
queriesToAdd.push(`getNode${name}s(filter: ${name}Input): [${name}]\n`);
// Create mutation
mutationsToAdd.push(`createNode${name}(input: ${name}CreateInput!): ${name}\n`);
mutationsToAdd.push(`updateNode${name}(input: ${name}UpdateInput!): ${name}\n`);
mutationsToAdd.push(`deleteNode${name}(${print(idFieldToInputValue(idField))}): Boolean\n`);
loggerInfo(`Added input type: ${yellow(name+'CreateInput')}`);
loggerInfo(`Added input type: ${yellow(name+'UpdateInput')}`);
loggerInfo(`Added query: ${yellow('getNode' + name)}`);
loggerInfo(`Added query: ${yellow('getNode' + name + 's')}`);
loggerInfo(`Added mutation: ${yellow('createNode' + name)}`);
loggerInfo(`Added mutation: ${yellow('updateNode' + name)}`);
loggerInfo(`Added mutation: ${yellow('deleteNode' + name)}`);
}
function addEdge(from, to, edgeName) {
if (!typesToAdd.some((str) => str.startsWith(`type ${edgeName}`))) {
// Create type
typesToAdd.push(`type ${edgeName} {\n _id: ID! @id\n}`);
// Create mutation
mutationsToAdd.push(`connectNode${from}ToNode${to}Edge${edgeName}(from_id: ID!, to_id: ID!): ${edgeName}\n`);
mutationsToAdd.push(`deleteEdge${edgeName}From${from}To${to}(from_id: ID!, to_id: ID!): Boolean\n`);
loggerInfo(`Added type for edge: ${yellow(edgeName)}`);
loggerInfo(`Added mutation: ${yellow(`connectNode${from}ToNode${to}Edge${edgeName}`)}`);
loggerInfo(`Added mutation: ${yellow(`deleteEdge${edgeName}From${from}To${to}`)}`);
}
}
function addFilterOptionsArguments(field) {
// filter
field.arguments.push({
kind: 'InputValueDefinition',
name: {
kind: 'Name',
value: 'filter'
},
type: {
kind: 'NamedType',
name: {
kind: 'Name',
value: field.type.type.name.value + 'Input'
}
}
});
// options
field.arguments.push({
kind: 'InputValueDefinition',
name: {
kind: 'Name',
value: 'options'
},
type: {
kind: 'NamedType',
name: {
kind: 'Name',
value: 'Options'
}
}
});
}
function getIdField(objTypeDef) {
return objTypeDef.fields.find(
field =>
field.directives && field.directives.some(directive => directive.name.value === 'id')
);
}
function createIdField() {
return {
kind: 'FieldDefinition',
name: { kind: 'Name', value: '_id' },
arguments: [],
type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } } },
directives: [
{ kind: 'Directive', name: { kind: 'Name', value: 'id' }, arguments: [] }
]
};
}
function idFieldToInputValue({ name, type }) {
return { kind: 'InputValueDefinition', name, type };
}
function getInputFields(objTypeDef) {
return objTypeDef.fields.filter(field => isScalar(nullable(field.type)));
}
function nullable(type) {
return type.kind === 'NonNullType' ? type.type : type;
}
function isScalar(type) {
const scalarTypes = ['String', 'Int', 'Float', 'Boolean', 'ID'];
return type.kind === 'NamedType' && scalarTypes.includes(type.name.value);
}
function inferGraphDatabaseDirectives(schemaModel) {
var currentType = '';
let referencedType = '';
let edgeName = '';
schemaModel.definitions.forEach(def => {
if (def.kind == 'ObjectTypeDefinition') {
if (!(def.name.value == 'Query' || def.name.value == 'Mutation')) {
currentType = def.name.value;
// Only add _id field to the object type if it doesn't have an ID field already
if (!getIdField(def)) {
def.fields.unshift(createIdField());
}
addNode(def);
const edgesTypeToAdd = [];
// add relationships
def.fields.forEach(field => {
if (field.type.type !== undefined) {
if (field.type.type.kind === 'NamedType' && field.type.type.name.value !== 'ID')
{
try {
if (field.type.kind === 'ListType')
addFilterOptionsArguments(field);
}
catch {}
try {
referencedType = field.type.type.name.value;
edgeName = referencedType + 'Edge';
loggerInfo("Infer graph database directive in type: " + yellow(currentType) + " field: " + yellow(field.name.value) + " referenced type: " + yellow(referencedType) + " graph relationship: " + yellow(edgeName));
addRelationshipDirective(field, edgeName, 'OUT');
addEdge(currentType, referencedType, edgeName);
if (!edgesTypeToAdd.includes(edgeName)) edgesTypeToAdd.push(edgeName);
}
catch {}
}
} else if (field.type.name.value !== 'String' &&
field.type.name.value !== 'Int' &&
field.type.name.value !== 'Float' &&
field.type.name.value !== 'Boolean') {
referencedType = field.type.name.value;
edgeName = referencedType + 'Edge';
loggerInfo("Infer graph database directive in type: " + yellow(currentType) + " field: " + yellow(field.name.value) + " referenced type: " + yellow(referencedType) + " graph relationship: " + yellow(edgeName));
addRelationshipDirective(field, edgeName, 'OUT');
addEdge(currentType, referencedType, edgeName);
if (!edgesTypeToAdd.includes(edgeName)) edgesTypeToAdd.push(edgeName);
}
});
// add edges
edgesTypeToAdd.forEach(edgeName => {
def.fields.push({
kind: "FieldDefinition",
name: { kind: "Name", value: lowercaseFirstCharacter(edgeName) },
arguments: [],
type: { kind: "NamedType", name: { kind: "Name", value: edgeName } },
directives: []
});
});
}
}
});
typesToAdd.push(`input Options {\n limit: Int\n}\n`);
return injectChanges(schemaModel);
}
function validatedSchemaModel (schemaModel, quietInput) {
quiet = quietInput;
if (!isGraphDBDirectives(schemaModel)) {
loggerInfo("The schema model does not contain any graph database directives.");
schemaModel = inferGraphDatabaseDirectives(schemaModel);
}
return schemaModel;
}
export { validatedSchemaModel };