forked from neo4j-graphql/neo4j-graphql-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
974 lines (878 loc) · 27.1 KB
/
utils.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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
import { print, parse } from 'graphql';
import { possiblyAddArgument } from './augment';
import { v1 as neo4j } from 'neo4j-driver';
import _ from 'lodash';
import filter from 'lodash/filter';
function parseArg(arg, variableValues) {
switch (arg.value.kind) {
case 'IntValue':
return parseInt(arg.value.value);
break;
case 'FloatValue':
return parseFloat(arg.value.value);
break;
case 'Variable':
return variableValues[arg.name.value];
break;
default:
return arg.value.value;
}
}
export function parseArgs(args, variableValues) {
if (!args || args.length === 0) {
return {};
}
return args.reduce((acc, arg) => {
acc[arg.name.value] = parseArg(arg, variableValues);
return acc;
}, {});
}
function getDefaultArguments(fieldName, schemaType) {
// get default arguments for this field from schema
try {
return schemaType._fields[fieldName].args.reduce((acc, arg) => {
acc[arg.name] = arg.defaultValue;
return acc;
}, {});
} catch (err) {
return {};
}
}
export function cypherDirectiveArgs(
variable,
headSelection,
schemaType,
resolveInfo
) {
const defaultArgs = getDefaultArguments(headSelection.name.value, schemaType);
const queryArgs = parseArgs(
headSelection.arguments,
resolveInfo.variableValues
);
let args = JSON.stringify(Object.assign(defaultArgs, queryArgs)).replace(
/\"([^(\")"]+)\":/g,
' $1: '
);
return args === '{}'
? `{this: ${variable}${args.substring(1)}`
: `{this: ${variable},${args.substring(1)}`;
}
export function isMutation(resolveInfo) {
return resolveInfo.operation.operation === 'mutation';
}
export function _isNamedMutation(name) {
return function(resolveInfo) {
return (
isMutation(resolveInfo) &&
resolveInfo.fieldName.split(/(?=[A-Z])/)[0].toLowerCase() ===
name.toLowerCase()
);
};
}
export const isCreateMutation = _isNamedMutation('create');
export const isAddMutation = _isNamedMutation('add');
export const isUpdateMutation = _isNamedMutation('update');
export const isDeleteMutation = _isNamedMutation('delete');
export const isRemoveMutation = _isNamedMutation('remove');
export function isAddRelationshipMutation(resolveInfo) {
return (
isAddMutation(resolveInfo) &&
resolveInfo.schema
.getMutationType()
.getFields()
[resolveInfo.fieldName].astNode.directives.some(
x => x.name.value === 'MutationMeta'
)
);
}
export function typeIdentifiers(returnType) {
const typeName = innerType(returnType).toString();
return {
variableName: lowFirstLetter(typeName),
typeName
};
}
export function isGraphqlScalarType(type) {
return (
type.constructor.name === 'GraphQLScalarType' ||
type.constructor.name === 'GraphQLEnumType'
);
}
export function isArrayType(type) {
return type.toString().startsWith('[');
}
export function lowFirstLetter(word) {
return word.charAt(0).toLowerCase() + word.slice(1);
}
export function innerType(type) {
return type.ofType ? innerType(type.ofType) : type;
}
// handles field level schema directives
// TODO: refactor to handle Query/Mutation type schema directives
const directiveWithArgs = (directiveName, args) => (schemaType, fieldName) => {
function fieldDirective(schemaType, fieldName, directiveName) {
return schemaType
.getFields()
[fieldName].astNode.directives.find(e => e.name.value === directiveName);
}
function directiveArgument(directive, name) {
return directive.arguments.find(e => e.name.value === name).value.value;
}
const directive = fieldDirective(schemaType, fieldName, directiveName);
const ret = {};
if (directive) {
Object.assign(
ret,
...args.map(key => ({
[key]: directiveArgument(directive, key)
}))
);
}
return ret;
};
export const cypherDirective = directiveWithArgs('cypher', ['statement']);
export const relationDirective = directiveWithArgs('relation', [
'name',
'direction'
]);
export function filtersFromSelections(selections, variableValues) {
if (
selections &&
selections.length &&
selections[0].arguments &&
selections[0].arguments.length
) {
return selections[0].arguments.reduce((result, x) => {
(result[x.name.value] = argumentValue(
selections[0],
x.name.value,
variableValues
)) || x.value.value;
return result;
}, {});
}
return {};
}
export function getFilterParams(filters, index) {
return Object.entries(filters).reduce((result, [key, value]) => {
result[key] = index
? {
value,
index
}
: value;
return result;
}, {});
}
export function innerFilterParams(filters, temporalArgs, paramKey) {
const temporalArgNames = temporalArgs ? temporalArgs.reduce( (acc, t) => {
acc.push(t.name.value);
return acc;
}, []) : [];
return Object.keys(filters).length > 0
? `{${Object.entries(filters)
// exclude temporal arguments
.filter(([key]) => !['first', 'offset', 'orderBy', ...temporalArgNames].includes(key))
.map(
([key, value]) =>
`${key}:${paramKey ? `$${paramKey}.` : '$'}${
typeof value.index === 'undefined' ? key : `${value.index}_${key}`
}`
)
.join(',')}}`
: '';
}
function argumentValue(selection, name, variableValues) {
let arg = selection.arguments.find(a => a.name.value === name);
if (!arg) {
return null;
} else {
const key = arg.value.name.value;
try {
return variableValues[key];
} catch (e) {
return argumentValue(selection, name, variableValues);
}
}
}
function argumentValue(selection, name, variableValues) {
let arg = selection.arguments.find(a => a.name.value === name);
if (!arg) {
return null;
} else {
return parseArg(arg, variableValues);
}
}
export function extractQueryResult({ records }, returnType) {
const { variableName } = typeIdentifiers(returnType);
let result = isArrayType(returnType)
? records.map(record => record.get(variableName))
: records.length
? records[0].get(variableName)
: null;
result = convertIntegerFields(result);
return result;
}
const convertIntegerFields = result => {
const keys = result ? Object.keys(result) : [];
let field = undefined;
let num = undefined;
keys.forEach(e => {
field = result[e];
if (neo4j.isInt(field)) {
num = neo4j.int(field);
if (neo4j.integer.inSafeRange(num)) {
result[e] = num.toString();
} else {
result[e] = num.toString();
}
} else if (typeof result[e] === 'object') {
return convertIntegerFields(result[e]);
}
});
return result;
};
export function computeSkipLimit(selection, variableValues) {
let first = argumentValue(selection, 'first', variableValues);
let offset = argumentValue(selection, 'offset', variableValues);
if (first === null && offset === null) return '';
if (offset === null) return `[..${first}]`;
if (first === null) return `[${offset}..]`;
return `[${offset}..${parseInt(offset) + parseInt(first)}]`;
}
export const computeOrderBy = (resolveInfo, selection) => {
const orderByVar = argumentValue(
resolveInfo.operation.selectionSet.selections[0],
'orderBy',
resolveInfo.variableValues
);
if (orderByVar == undefined) {
return '';
} else {
const splitIndex = orderByVar.lastIndexOf('_');
const order = orderByVar.substring(splitIndex + 1);
const orderBy = orderByVar.substring(0, splitIndex);
const { variableName } = typeIdentifiers(resolveInfo.returnType);
return ` ORDER BY ${variableName}.${orderBy} ${
order === 'asc' ? 'ASC' : 'DESC'
} `;
}
};
export const possiblySetFirstId = ({
args,
statements,
params
}) => {
const arg = args.find(e => getFieldValueType(e) === "ID");
// arg is the first ID field if it exists, and we set the value
// if no value is provided for the field name (arg.name.value) in params
if(arg && arg.name.value && params[arg.name.value] === undefined) {
statements.push(`${arg.name.value}: apoc.create.uuid()`);
}
return statements;
}
export const getQueryArguments = (resolveInfo) => {
return resolveInfo.schema.getQueryType().getFields()[
resolveInfo.fieldName
].astNode.arguments;
}
export const getMutationArguments = (resolveInfo) => {
return resolveInfo.schema.getMutationType().getFields()[
resolveInfo.fieldName
].astNode.arguments;
}
const decideCypherFunction = (fieldAst) => {
let cypherFunction = undefined;
const type = fieldAst ? getNamedType(fieldAst.type).name.value : '';
switch(type) {
case "_Neo4jTimeInput": cypherFunction = "time"; break;
case "_Neo4jDateInput": cypherFunction = "date"; break;
case "_Neo4jDateTimeInput": cypherFunction = "datetime"; break;
case "_Neo4jLocalTimeInput": cypherFunction = "localtime"; break;
case "_Neo4jLocalDateTimeInput": cypherFunction = "localdatetime"; break;
default: break;
}
return cypherFunction;
}
export const buildCypherParameters = ({
args,
statements=[],
params,
paramKey
}) => {
const dataParams = paramKey ? params[paramKey] : params;
const paramKeys = dataParams ? Object.keys(dataParams) : [];
if(args) {
statements = paramKeys.reduce( (acc, paramName) => {
const param = paramKey ? params[paramKey][paramName] : params[paramName];
// The AST definition of the argument of the same name as this param
const fieldAst = args.find(arg => arg.name.value === paramName);
if(fieldAst) {
const formatted = param.formatted;
const cypherFunction = decideCypherFunction(fieldAst);
if(cypherFunction) {
// Prefer only using formatted, if provided
if(formatted) {
if(paramKey) {
params[paramKey][paramName] = formatted;
}
else {
params[paramName] = formatted;
}
acc.push(`${paramName}: ${cypherFunction}($${
paramKey
? `${paramKey}.`
: ''}${paramName})`
);
}
else {
// build all arguments for given cypherFunction
acc.push(`${paramName}: ${cypherFunction}({${
temporalFieldParam(paramName, param, paramKey)
}})`);
}
}
else {
// normal case
acc.push(`${paramName}:$${paramKey ? `${paramKey}.` : ''}${paramName}`);
}
}
return acc;
}, statements);
}
if(paramKey) {
params[paramKey] = dataParams;
}
return [params, statements];
}
const temporalFieldParam = (paramName, param, paramKey) => {
return param.formatted === undefined
? Object.keys(param).reduce( (acc, t) => {
if(Number.isInteger(param[t])) {
acc.push(`${t}: toInteger($${paramKey ? `${paramKey}.` : '' }${paramName}.${t})`);
}
else {
acc.push(`${t}: $${paramKey ? `${paramKey}.` : '' }${paramName}.${t}`);
}
return acc;
}, []).join(',')
: '';
}
export function extractSelections(selections, fragments) {
// extract any fragment selection sets into a single array of selections
return selections.reduce((acc, cur) => {
if (cur.kind === 'FragmentSpread') {
const recursivelyExtractedSelections = extractSelections(
fragments[cur.name.value].selectionSet.selections,
fragments
);
return [...acc, ...recursivelyExtractedSelections];
} else {
return [...acc, cur];
}
}, []);
}
export function fixParamsForAddRelationshipMutation(params, resolveInfo) {
// FIXME: find a better way to map param name in schema to datamodel
let mutationMeta, fromTypeArg, toTypeArg;
try {
mutationMeta = resolveInfo.schema
.getMutationType()
.getFields()
[resolveInfo.fieldName].astNode.directives.filter(x => {
return x.name.value === 'MutationMeta';
})[0];
} catch (e) {
throw new Error(
'Missing required MutationMeta directive on add relationship directive'
);
}
try {
fromTypeArg = mutationMeta.arguments.filter(x => {
return x.name.value === 'from';
})[0];
toTypeArg = mutationMeta.arguments.filter(x => {
return x.name.value === 'to';
})[0];
} catch (e) {
throw new Error(
'Missing required argument in MutationMeta directive (relationship, from, or to)'
);
}
//TODO: need to handle one-to-one and one-to-many
const fromType = fromTypeArg.value.value,
toType = toTypeArg.value.value,
fromVar = lowFirstLetter(fromType),
toVar = lowFirstLetter(toType),
fromParam = resolveInfo.schema
.getMutationType()
.getFields()
[resolveInfo.fieldName].astNode.arguments[0].name.value.substr(
fromVar.length
),
toParam = resolveInfo.schema
.getMutationType()
.getFields()
[resolveInfo.fieldName].astNode.arguments[1].name.value.substr(
toVar.length
);
params[toParam] =
params[
resolveInfo.schema.getMutationType().getFields()[
resolveInfo.fieldName
].astNode.arguments[1].name.value
];
params[fromParam] =
params[
resolveInfo.schema.getMutationType().getFields()[
resolveInfo.fieldName
].astNode.arguments[0].name.value
];
delete params[
resolveInfo.schema.getMutationType().getFields()[resolveInfo.fieldName]
.astNode.arguments[1].name.value
];
delete params[
resolveInfo.schema.getMutationType().getFields()[resolveInfo.fieldName]
.astNode.arguments[0].name.value
];
return params;
}
export const isKind = (type, kind) => type && type.kind === kind;
export const isListType = (type, isList = false) => {
if (!isKind(type, 'NamedType')) {
if (isKind(type, 'ListType')) isList = true;
return isListType(type.type, isList);
}
return isList;
};
export const parameterizeRelationFields = fields => {
let name = '';
return Object.keys(fields)
.reduce((acc, t) => {
name = fields[t].name.value;
acc.push(`${name}:$data.${name}`);
return acc;
}, [])
.join(',');
};
export const getRelationTypeDirectiveArgs = relationshipType => {
const directive = relationshipType.directives.find(
e => e.name.value === 'relation'
);
return directive
? {
name: directive.arguments.find(e => e.name.value === 'name').value
.value,
from: directive.arguments.find(e => e.name.value === 'from').value
.value,
to: directive.arguments.find(e => e.name.value === 'to').value.value
}
: undefined;
};
export const getFieldArgumentsFromAst = (field, typeName, fieldIsList) => {
let fieldArgs = field.arguments ? field.arguments : [];
let augmentedArgs = [...fieldArgs];
if (fieldIsList) {
augmentedArgs = possiblyAddArgument(augmentedArgs, 'first', 'Int');
augmentedArgs = possiblyAddArgument(augmentedArgs, 'offset', 'Int');
augmentedArgs = possiblyAddArgument(
augmentedArgs,
'orderBy',
`_${typeName}Ordering`
);
}
const args = augmentedArgs
.reduce((acc, t) => {
acc.push(print(t));
return acc;
}, [])
.join('\n');
return args.length > 0 ? `(${args})` : '';
};
export const getRelationMutationPayloadFieldsFromAst = relatedAstNode => {
let isList = false;
let fieldName = '';
return relatedAstNode.fields
.reduce((acc, t) => {
fieldName = t.name.value;
if (fieldName !== 'to' && fieldName !== 'from') {
isList = isListType(t);
// Use name directly in order to prevent requiring required fields on the payload type
acc.push(
`${fieldName}: ${isList ? '[' : ''}${getNamedType(t).name.value}${
isList ? `]` : ''
}${print(t.directives)}`
);
}
return acc;
}, [])
.join('\n');
};
export const getFieldValueType = type => {
if (type.kind !== 'NamedType') {
return getFieldValueType(type.type);
}
return type.name.value;
};
export const getNamedType = type => {
if (type.kind !== 'NamedType') {
return getNamedType(type.type);
}
return type;
};
export const isBasicScalar = name => {
return (
name === 'ID' ||
name === 'String' ||
name === 'Float' ||
name === 'Int' ||
name === 'Boolean'
);
};
const firstNonNullAndIdField = fields => {
let valueTypeName = '';
return fields.find(e => {
valueTypeName = getNamedType(e).name.value;
return (
e.name.value !== '_id' &&
e.type.kind === 'NonNullType' &&
valueTypeName === 'ID'
);
});
};
const firstIdField = fields => {
let valueTypeName = '';
return fields.find(e => {
valueTypeName = getNamedType(e).name.value;
return e.name.value !== '_id' && valueTypeName === 'ID';
});
};
const firstNonNullField = fields => {
let valueTypeName = '';
return fields.find(e => {
valueTypeName = getNamedType(e).name.value;
return valueTypeName === 'NonNullType';
});
};
const firstField = fields => {
return fields.find(e => {
return e.name.value !== '_id';
});
};
export const getPrimaryKey = astNode => {
const fields = astNode.fields;
let pk = firstNonNullAndIdField(fields);
if (!pk) {
pk = firstIdField(fields);
}
if (!pk) {
pk = firstNonNullField(fields);
}
if (!pk) {
pk = firstField(fields);
}
return pk;
};
export const getTypeDirective = (relatedAstNode, name) => {
return relatedAstNode.directives
? relatedAstNode.directives.find(e => e.name.value === name)
: undefined;
};
export const getFieldDirective = (field, directive) => {
return field && field.directives.find(e => e.name.value === directive);
};
export const isNonNullType = (type, isRequired = false, parent = {}) => {
if (!isKind(type, 'NamedType')) {
return isNonNullType(type.type, isRequired, type);
}
if (isKind(parent, 'NonNullType')) {
isRequired = true;
}
return isRequired;
};
export const createOperationMap = type => {
const fields = type ? type.fields : [];
return fields.reduce((acc, t) => {
acc[t.name.value] = t;
return acc;
}, {});
};
export const isNodeType = astNode => {
// TODO: check for @ignore and @model directives
return (
astNode &&
// must be graphql object type
astNode.kind === 'ObjectTypeDefinition' &&
// is not Query or Mutation type
astNode.name.value !== 'Query' &&
astNode.name.value !== 'Mutation' &&
// does not have relation type directive
getTypeDirective(astNode, 'relation') === undefined &&
// does not have from and to fields; not relation type
astNode.fields &&
astNode.fields.find(e => e.name.value === 'from') === undefined &&
astNode.fields.find(e => e.name.value === 'to') === undefined
);
};
export const parseFieldSdl = sdl => {
return sdl
? parse(`type fieldToParse { ${sdl} }`).definitions[0].fields[0]
: {};
};
export const getRelationDirection = relationDirective => {
let direction = {};
try {
direction = relationDirective.arguments.filter(
a => a.name.value === 'direction'
)[0];
return direction.value.value;
} catch (e) {
// FIXME: should we ignore this error to define default behavior?
throw new Error('No direction argument specified on @relation directive');
}
};
export const getRelationName = relationDirective => {
let name = {};
try {
name = relationDirective.arguments.filter(a => a.name.value === 'name')[0];
return name.value.value;
} catch (e) {
// FIXME: should we ignore this error to define default behavior?
throw new Error('No name argument specified on @relation directive');
}
};
/**
* Render safe a variable name according to cypher rules
* @param {String} i input variable name
* @returns {String} escaped text suitable for interpolation in cypher
*/
export const safeVar = i => {
// There are rare cases where the var input is an object and has to be stringified
// to produce the right output.
const asStr = `${i}`;
// Rules: https://neo4j.com/docs/developer-manual/current/cypher/syntax/naming/
return '`' + asStr.replace(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/g, '_') + '`';
};
/**
* Render safe a label name by enclosing it in backticks and escaping any
* existing backtick if present.
* @param {String} l a label name
* @returns {String} an escaped label name suitable for cypher concat
*/
export const safeLabel = l => {
const asStr = `${l}`;
const escapeInner = asStr.replace(/\`/g, '\\`');
return '`' + escapeInner + '`';
};
export const printTypeMap = typeMap => {
return print({
kind: 'Document',
definitions: Object.values(typeMap)
});
};
export const decideNestedVariableName = ({
schemaTypeRelation,
innerSchemaTypeRelation,
variableName,
fieldName,
rootVariableNames
}) => {
if (rootVariableNames) {
// Only show up for relation mutations
return rootVariableNames[fieldName];
}
if (schemaTypeRelation) {
const fromTypeName = schemaTypeRelation.from;
const toTypeName = schemaTypeRelation.to;
if (fromTypeName === toTypeName) {
if (fieldName === 'from' || fieldName === 'to') {
return variableName + '_' + fieldName;
} else {
// Case of a reflexive relationship type's directed field
// being renamed to its node type value
// ex: from: User -> User: User
return variableName;
}
}
} else {
// Types without @relation directives are assumed to be node types
// and only node types can have fields whose values are relation types
if (innerSchemaTypeRelation) {
// innerSchemaType is a field payload type using a @relation directive
if (innerSchemaTypeRelation.from === innerSchemaTypeRelation.to) {
return variableName;
}
} else {
// related types are different
return variableName + '_' + fieldName;
}
}
return variableName + '_' + fieldName;
};
export const extractTypeMapFromTypeDefs = typeDefs => {
// TODO: accept alternative typeDefs formats (arr of strings, ast, etc.)
// into a single string for parse, add validatation
const astNodes = parse(typeDefs).definitions;
return astNodes.reduce((acc, t) => {
if (t.name) acc[t.name.value] = t;
return acc;
}, {});
};
export const addDirectiveDeclarations = typeMap => {
// overwrites any provided directive declarations for system directive names
typeMap['cypher'] = parse(
`directive @cypher(statement: String) on FIELD_DEFINITION`
);
typeMap['relation'] = parse(
`directive @relation(name: String, direction: _RelationDirections, from: String, to: String) on FIELD_DEFINITION | OBJECT`
);
typeMap['MutationMeta'] = parse(
`directive @MutationMeta(relationship: String, from: String, to: String) on FIELD_DEFINITION`
);
typeMap['_RelationDirections'] = parse(`enum _RelationDirections { IN OUT }`);
return typeMap;
};
export const initializeMutationParams = ({
resolveInfo,
mutationTypeCypherDirective,
otherParams,
first,
offset
}) => {
return (isCreateMutation(resolveInfo) || isUpdateMutation(resolveInfo)) &&
!mutationTypeCypherDirective
? { params: otherParams, ...{ first, offset } }
: { ...otherParams, ...{ first, offset } };
}
export const getQueryCypherDirective = (resolveInfo) => {
return resolveInfo.schema
.getQueryType()
.getFields()
[resolveInfo.fieldName].astNode.directives.find(x => {
return x.name.value === 'cypher';
});
}
export const getMutationCypherDirective = (resolveInfo) => {
return resolveInfo.schema
.getMutationType()
.getFields()
[resolveInfo.fieldName].astNode.directives.find(x => {
return x.name.value === 'cypher';
});
}
export const getOuterSkipLimit = first =>
`SKIP $offset${first > -1 ? ' LIMIT $first' : ''}`;
export const getQuerySelections = (resolveInfo) => {
const filteredFieldNodes = filter(
resolveInfo.fieldNodes,
n => n.name.value === resolveInfo.fieldName
);
// FIXME: how to handle multiple fieldNode matches
return extractSelections(
filteredFieldNodes[0].selectionSet.selections,
resolveInfo.fragments
);
}
export const getMutationSelections = (resolveInfo) => {
let selections = getQuerySelections(resolveInfo);
if (selections.length === 0) {
// FIXME: why aren't the selections found in the filteredFieldNode?
selections = extractSelections(
resolveInfo.operation.selectionSet.selections,
resolveInfo.fragments
);
}
return selections;
}
export const filterNullParams = ({
offset,
first,
otherParams
}) => {
return Object.entries({
...{ offset, first },
...otherParams
}).reduce(
([nulls, nonNulls], [key, value]) => {
if (value === null) {
nulls[key] = value;
} else {
nonNulls[key] = value;
}
return [nulls, nonNulls];
},
[{}, {}]
);
}
export const isTemporalType = (name) => {
return name === "_Neo4jTime" ||
name === "_Neo4jDate" ||
name === "_Neo4jDateTime" ||
name === "_Neo4jLocalTime" ||
name === "_Neo4jLocalDateTime";
}
const isTemporalInputType = (name) => {
return name === "_Neo4jTimeInput" ||
name === "_Neo4jDateInput" ||
name === "_Neo4jDateTimeInput" ||
name === "_Neo4jLocalTimeInput" ||
name === "_Neo4jLocalDateTimeInput";
}
export const isTemporalField = (schemaType, name) => {
const type = schemaType ? schemaType.name : '';
return isTemporalType(type) &&
name === "year" ||
name === "month" ||
name === "day" ||
name === "hour" ||
name === "minute" ||
name === "second" ||
name === "microsecond" ||
name === "millisecond" ||
name === "nanosecond" ||
name === "timezone" ||
name === "formatted";
}
export const getTemporalArguments = (args) => {
return args ? args.reduce( (acc, t) => {
const fieldType = getNamedType(t.type).name.value;
if(isTemporalInputType(fieldType)) acc.push(t);
return acc;
}, []) : [];
}
export function temporalPredicateClauses(filters, variableName, temporalArgs, parentParam) {
return temporalArgs.reduce( (acc, t) => {
// For every temporal argument
const argName = t.name.value;
let temporalParam = filters[argName];
if(temporalParam) {
// If a parameter value has been provided for it check whether
// the provided param value is in an indexed object for a nested argument
const paramIndex = temporalParam.index;
const paramValue = temporalParam.value;
// If it is, set and use its .value
if(paramValue) temporalParam = paramValue;
if(temporalParam["formatted"]) {
// Only the dedicated 'formatted' arg is used if it is provided
const cypherFunction = decideCypherFunction(t);
acc.push(`${variableName}.${argName} = ${cypherFunction}($${
// use index if provided, for nested arguments
typeof paramIndex === 'undefined'
? `${parentParam ? `${parentParam}.` : ''}${argName}.formatted`
: `${parentParam ? `${parentParam}.` : ''}${paramIndex}_${argName}.formatted`
})`);
}
else {
Object.keys(temporalParam).forEach(e => {
acc.push(`${variableName}.${argName}.${e} = $${
typeof paramIndex === 'undefined'
? `${parentParam ? `${parentParam}.` : ''}${argName}`
: `${parentParam ? `${parentParam}.` : ''}${paramIndex}_${argName}`
}.${e}`);
});
}
}
return acc;
}, []);
}