-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResolvers.js
More file actions
1300 lines (1138 loc) · 53 KB
/
Resolvers.js
File metadata and controls
1300 lines (1138 loc) · 53 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
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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//import * as neo4j from 'neo4j-driver';
import {ValidationError} from 'apollo-server';
import {cypherQuery} from 'neo4j-graphql-js';
import GraphQLUpload from 'graphql-upload/GraphQLUpload.mjs';
import fs from 'fs'
import path from 'path'
import crypto from 'crypto';
import { GraphQLScalarType, Kind, GraphQLError } from 'graphql';
import {schemaDeleteMap, schemaMap} from './SchemaMaps.js';
import {uploadFile, renameFile, deleteFile} from './ImageManagement.js';
const isPublic = async (session, pbotID) => {
const queryStr = `
MATCH
(n)-[:ELEMENT_OF]->(:Group {name: "public"})
WHERE
n.pbotID = $pbotID
RETURN
n
`;
console.log(queryStr);
const result = await session.run(
queryStr,
{pbotID: pbotID}
);
return result.records.length > 0;
}
const isSynonym = async (session, otus) => {
const queryStr = `
MATCH
(:OTU {pbotID: "${otus[0]}"})-[:SAME_AS]->(s:Synonym)<-[:SAME_AS]-(:OTU {pbotID: "${otus[1]}"})
RETURN
s
`;
console.log(queryStr);
const result = await session.run(
queryStr,
{otus: otus}
);
return result.records.length > 0;
}
const getPerson = async (session, email) => {
const queryStr = `
MATCH
(p:Person {email: "${email}"})
RETURN
p
`;
console.log(queryStr);
const result = await session.run(
queryStr,
{email: email}
)
return result.records.length > 0 ? result.records[0].get(0) : null;
}
const getGroups = async (session, data) => {
const rootID = data.schemaID || data.descriptionID || data.collection || data.imageOf || null;
if (rootID !== null) {
const queryStr = `
MATCH
(n)-[:ELEMENT_OF]-(g:Group)
WHERE
n.pbotID = "${rootID}"
RETURN
g
`;
console.log(queryStr);
const result = await session.run(
queryStr,
{rootID: rootID}
)
console.log("------result----------");
console.log(result);
console.log("records returned: " + result.records.length)
const res = result.records.map((rec) => (rec.get(0).properties.pbotID));
console.log("res");
console.log(res);
return res;
} else {
throw new ValidationError(`Cannot find groups`); //TODO: good enough?
}
}
const getRelationships = async (session, pbotID, relationships, enteredByPersonID, nodeType) => {
//This variation with nodeType and enteredByID is to handle Group deletion.
//If a group has been cleaned out, it will still have one ELEMENT_OF to itself and one
//MEMBER_OF to the current user. But we want to delete it anyhow. Leaving the original
//query ghosted for now.
let queryStr = relationships.reduce((str, relationship) => `
${str}
MATCH
(n)${relationship.direction === "in" ? "<-" : "-"}[:${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(r)
WHERE n.pbotID="${pbotID}" ${nodeType === "Group" ?
`AND r.pbotID<>"${enteredByPersonID}" AND r.pbotID<>n.pbotID` :
''
}
RETURN
r
UNION ALL
`,'');
/*
//Original
let queryStr = relationships.reduce((str, relationship) => `
${str}
MATCH
(n)${relationship.direction === "in" ? "<-" : "-"}[:${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(r)
WHERE n.pbotID="${pbotID}"
RETURN
r
UNION ALL
`,'');
*/
queryStr = queryStr.substring(0, queryStr.lastIndexOf("UNION ALL"))
console.log(queryStr);
//If our string is empty, there is nothing to query (i.e. no relationships to search for). Return empty array.
if (queryStr === '') return [];
let result;
result = await session.run(
queryStr,
{pbotID: pbotID}
)
console.log("------result----------");
console.log(result);
console.log("records returned: " + result.records.length)
const res = result.records.map((rec) => ({...rec.get(0).properties, nodeType: rec.get(0).labels[0]}));
console.log("res");
console.log(res);
return res;
}
const handleDelete = async (session, nodeType, pbotID, enteredByPersonID, relationships) => {
console.log("handleDelete");
let queryStr = `
MATCH
(baseNode:${nodeType} {pbotID: "${pbotID}"}),
(ePerson:Person {pbotID: "${enteredByPersonID}"})
WITH baseNode, ePerson
CREATE
(baseNode)-[:ENTERED_BY {timestamp: datetime(), type:"DELETE"}]->(ePerson)
WITH baseNode
REMOVE baseNode:${nodeType} SET baseNode:_${nodeType}
WITH baseNode
`;
queryStr = relationships.reduce((str, relationship) => `
${str}
OPTIONAL MATCH (baseNode)${relationship.direction === "in" ? "<-" : "-"}[rel:${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(remoteNode)
CALL apoc.do.when(
rel IS NOT NULL,
"CREATE (baseNode)${relationship.direction === "in" ? "<-" : "-"}[archivedRel:_${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(node) SET archivedRel = rel DELETE rel RETURN baseNode",
"RETURN baseNode",
{baseNode: baseNode, node: remoteNode, rel: rel}
) YIELD value
WITH distinct value.baseNode AS baseNode
`, queryStr);
queryStr = `
${queryStr}
RETURN {
pbotID: baseNode.pbotID
}
`;
console.log(queryStr);
const result = await session.run(queryStr);
return result;
}
const handleUpdate = async (session, nodeType, data) => {
console.log("handleUpdate");
const pbotID = data.pbotID;
const enteredByPersonID = data.enteredByPersonID
let properties;
let relationships;
if (data.groupCascade) {
//all we want to do in this case is update the groups
properties = [];
relationships = [{
type: "ELEMENT_OF",
direction: "out",
graphqlName: "groups",
required: true,
updatable: true
}];
} else {
properties = schemaMap[nodeType].properties || [];
relationships = schemaMap[nodeType].relationships || [];
relationships = relationships.filter(r => r.updatable);
}
console.log("relationships");
console.log(relationships);
//Get base node and create new ENTERED_BY relationship
let queryStr = `
MATCH
(baseNode:${nodeType} {pbotID: "${pbotID}"}),
(ePerson:Person {pbotID: "${enteredByPersonID}"})
WITH baseNode, ePerson
CREATE
(baseNode)-[eb:ENTERED_BY {timestamp: datetime(), type:"EDIT"}]->(ePerson)
WITH baseNode, eb
`;
//Copy old property values into ENTERED_BY
queryStr = properties.reduce((str, property) => {
if (data[property]) {
if ("location" === property) { //More special handling for location
return `
${str}
CALL apoc.do.case([
baseNode.${property} IS NULL,
"SET eb.${property} = 'not present' RETURN eb",
baseNode.${property}.latitude <> ${JSON.stringify(data[property].latitude)} or baseNode.${property}.longitude <> ${JSON.stringify(data[property].longitude)},
"SET eb.${property} = baseNode.${property} RETURN eb"],
"RETURN eb",
{baseNode: baseNode, eb:eb}
) YIELD value
WITH baseNode, eb
`
} else {
return `
${str}
CALL apoc.do.case([
baseNode.${property} IS NULL,
"SET eb.${property} = 'not present' RETURN eb",
baseNode.${property} <> ${JSON.stringify(data[property])},
"SET eb.${property} = baseNode.${property} RETURN eb"],
"RETURN eb",
{baseNode: baseNode, eb:eb}
) YIELD value
WITH baseNode, eb
`
}
} else {
return `
${str}
CALL apoc.do.when (
baseNode.${property} IS NOT NULL,
"SET eb.${property} = baseNode.${property} RETURN eb",
"RETURN eb",
{baseNode: baseNode, eb:eb}
) YIELD value
WITH baseNode, eb
`
}
}, queryStr);
//Copy old relationships (as pbotID arrays) into ENTERED_BY. Also, go ahead and delete the relationships here for convenience.
//I'm not going to lie: this code is pretty stinky. In order to track changes to relationship properties and get them recorded
//in the ENTERED_BY, we have to create these weird string concats with the remote node ID and the properties. This is then
//used by an apoc disjunction test in the cypher. This is made a bit more ugly yet by the fact that I have chosen to support
//the original array or ID strings as well as the new array of objects.
queryStr = relationships.reduce((str, relationship) => {
if (Array.isArray(data[relationship.graphqlName])) {
let newRemoteIDs = [];
if (data[relationship.graphqlName].length > 0) {
newRemoteIDs = data[relationship.graphqlName].map(r => {
console.log(r);
let retStr;
if (typeof r === "string") {
retStr = r + "{}";
} else {
retStr = r.pbotID + JSON.stringify(Object.keys(r).reduce((t,propKey) => {
console.log(propKey);
if ("pbotID" !== propKey) {
console.log(r[propKey]);
t[propKey] = r[propKey];
}
return t;
}, {}));
}
console.log(retStr);
return retStr;
});
}
console.log("newRemoteIDs");
console.log(newRemoteIDs);
return `
${str}
OPTIONAL MATCH (baseNode)${relationship.direction === "in" ? "<-" : "-"}[rel:${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(remoteNode)
WITH baseNode, eb, collect(remoteNode.pbotID + apoc.convert.toJson(properties(rel))) AS remoteNodeIDs, collect(apoc.convert.toJson(rel)) AS oldRelsJSON, collect(rel) AS oldRels
FOREACH (r IN oldRels | DELETE r)
WITH distinct baseNode, remoteNodeIDs, oldRelsJSON, apoc.coll.disjunction(remoteNodeIDs, ${JSON.stringify(newRemoteIDs)} ) AS diffList, eb
CALL
apoc.do.case([
size(remoteNodeIDs) = 0 AND size(diffList) <> 0,
"SET eb.${relationship.graphqlName} = 'not present' RETURN eb",
size(diffList)<>0,
"SET eb.${relationship.graphqlName} = oldRelsJSON RETURN eb"],
"RETURN eb",
{diffList: diffList, oldRelsJSON: oldRelsJSON, eb: eb}
)
YIELD value
WITH baseNode, eb
`
} else { //single relationship, no array
if (data[relationship.graphqlName]) {
const newRemoteID = typeof data[relationship.graphqlName][0] === "string" ?
data[relationship.graphqlName] + "{}" :
r.pbotID + JSON.stringify(Object.keys(r).reduce((t,propKey) => {
console.log(propKey);
if ("pbotID" !== propKey) {
console.log(r[propKey]);
t[propKey] = r[propKey];
}
return t;
}, {}));
console.log("newRemoteID");
console.log(newRemoteID);
return `
${str}
OPTIONAL MATCH (baseNode)${relationship.direction === "in" ? "<-" : "-"}[rel:${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(remoteNode)
WITH baseNode, eb, remoteNode, remoteNode.pbotID + apoc.convert.toJson(properties(rel)) AS remoteNodeID, apoc.convert.toJson(rel) AS relJSON, rel
DELETE rel
WITH baseNode, eb, remoteNode, remoteNodeID, relJSON
CALL apoc.do.case([
remoteNode IS NULL,
"SET eb.${relationship.graphqlName} = 'not present' RETURN eb",
remoteNodeID <> ${JSON.stringify(newRemoteID)},
"SET eb.${relationship.graphqlName} = relJSON RETURN eb"],
"RETURN eb",
{remoteNode: remoteNode, remoteNodeID: remoteNodeID, relJSON: relJSON, eb: eb}
) YIELD value
WITH baseNode, eb
`
} else {
return `
${str}
OPTIONAL MATCH (baseNode)${relationship.direction === "in" ? "<-" : "-"}[rel:${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(remoteNode)
WITH baseNode, eb, remoteNode, apoc.convert.toJson(rel) AS relJSON, rel
DELETE rel
WITH baseNode, eb, remoteNode, relJSON
CALL apoc.do.when(
remoteNode IS NOT NULL,
"SET eb.${relationship.graphqlName} = relJSON RETURN eb",
"RETURN eb",
{remoteNode: remoteNode, relJSON: relJSON, eb: eb}
) YIELD value
WITH baseNode, eb
`
}
}
}, queryStr);
//Set new property values in base node
queryStr += `
SET
`;
//location prop needs special handling
queryStr = properties.reduce((str, property) => `
${str}
baseNode.${property} = ${"location" === property ?
`Point({latitude: ${data[property].latitude}, longitude: ${data[property].longitude}}),`
:
`${JSON.stringify(data[property])},`
}
`, queryStr);
queryStr = `
${queryStr.slice(0, queryStr.lastIndexOf(','))}
WITH baseNode
`;
/*
//Create new relationships
queryStr = relationships.reduce((str, relationship) => {
if (data[relationship.graphqlName] && data[relationship.graphqlName].length > 0) {
return `
${str}
UNWIND ${JSON.stringify(data[relationship.graphqlName])} AS iD
CALL
apoc.do.when(
iD IS NULL,
"RETURN baseNode",
"MATCH (remoteNode) WHERE remoteNode.pbotID = iD CREATE (baseNode)${relationship.direction === "in" ? "<-" : "-"}[:${relationship.type}]${relationship.direction === "in" ? "-" : "->"}(remoteNode) RETURN baseNode",
{iD:iD, baseNode:baseNode}
) YIELD value
WITH distinct baseNode
`
} else {
return str;
}
}, queryStr);
*/
//Create new relationships
queryStr = relationships.reduce((str, relationship) => { //iterate the relationship types for the node type
if (data[relationship.graphqlName] && data[relationship.graphqlName].length > 0) { //if there is data for the relationship type
//For singular relationships, only the pbotID string is passed. We need to encapsulte that in an array for the following logic
if (!Array.isArray(data[relationship.graphqlName])) data[relationship.graphqlName] = [data[relationship.graphqlName]];
return data[relationship.graphqlName].reduce((str, relInstance) => { //iterate the instances of this relationship type
let remoteID;
let relProps = '';
if (relationship.properties) {
console.log("relationship.properties");
remoteID = relInstance.pbotID;
relProps = relationship.properties.reduce((str, prop) => { //iterate each property to build string for create
return (prop !== "pbotID" && relInstance[prop]) ?
`${str}${prop}: "${relInstance[prop]}",` :
`${str}`;
}, '');
} else {
remoteID = relInstance; //For relationships without properties, only the pbotID string is passed
}
relProps = "{" + relProps.replace(/,$/,'') + "}"; //trim final comma and wrap in brackets
console.log("relProps");
console.log(relProps);
return `
${str}
MATCH (remoteNode) WHERE remoteNode.pbotID = "${remoteID}"
CREATE (baseNode)${relationship.direction === "in" ? "<-" : "-"}[:${relationship.type} ${relProps}]${relationship.direction === "in" ? "-" : "->"}(remoteNode)
WITH baseNode
`;
}, str);
} else {
if (relationship.required) {
throw new ValidationError(`Missing required relationship ${relationship.graphqlName}`);
} else {
return str;
}
}
}, queryStr);
queryStr = `
${queryStr}
RETURN {
pbotID: baseNode.pbotID
}
`;
console.log(queryStr);
const result = await session.run(queryStr);
return result;
}
const handleCreate = async (session, nodeType, data) => {
console.log("handleCreate");
console.log(data);
console.log(data.groups);
const pbotID = data.pbotID;
const enteredByPersonID = data.enteredByPersonID
const properties = schemaMap[nodeType].properties || [];
const relationships = schemaMap[nodeType].relationships || [];
//Get person node and create new ENTERED_BY relationship
let queryStr = `
MATCH
(ePerson:Person {pbotID: "${enteredByPersonID}"})
WITH ePerson
CREATE
(baseNode:${nodeType} {
pbotID: apoc.create.uuid()})-[eb:ENTERED_BY {timestamp: datetime(), type:"CREATE"}]->(ePerson)
WITH baseNode, ePerson
SET
`;
//location prop needs special handling
queryStr = properties.reduce((str, property) => `
${str}
baseNode.${property} = ${"location" === property ?
`Point({latitude: ${data[property].latitude}, longitude: ${data[property].longitude}}),`
:
`${JSON.stringify(data[property])},`
}
`, queryStr);
queryStr = `
${queryStr.slice(0, queryStr.lastIndexOf(','))}
WITH baseNode, ePerson
`;
//Create new relationships
queryStr = relationships.reduce((str, relationship) => { //iterate the relationship types for the node type
if (data[relationship.graphqlName] && data[relationship.graphqlName].length > 0) { //if there is data for the relationship type
//For singular relationships, only the pbotID string is passed. We need to encapsulte that in an array for the following logic
if (!Array.isArray(data[relationship.graphqlName])) data[relationship.graphqlName] = [data[relationship.graphqlName]];
return data[relationship.graphqlName].reduce((str, relInstance) => { //iterate the instances of this relationship type
let remoteID;
let relProps = '';
if (relationship.properties) {
console.log("relationship.properties");
remoteID = relInstance.pbotID;
relProps = relationship.properties.reduce((str, prop) => { //iterate each property to build string for create
return (prop !== "pbotID" && relInstance[prop]) ?
`${str}${prop}: "${relInstance[prop]}",` :
`${str}`;
}, '');
} else {
remoteID = relInstance; //For relationships without properties, only the pbotID string is passed
}
relProps = "{" + relProps.replace(/,$/,'') + "}"; //trim final comma and wrap in brackets
console.log("relProps");
console.log(relProps);
return `
${str}
MATCH (remoteNode) WHERE remoteNode.pbotID = "${remoteID}"
CREATE (baseNode)${relationship.direction === "in" ? "<-" : "-"}[:${relationship.type} ${relProps}]${relationship.direction === "in" ? "-" : "->"}(remoteNode)
WITH baseNode, ePerson
`;
}, str);
} else {
if (relationship.required) {
throw new ValidationError(`Missing required relationship ${relationship.graphqlName}`);
} else {
return str;
}
}
}, queryStr);
//Groups must be elements of themselves; the creator must be a member, if not already
queryStr = "Group" === nodeType ? `
${queryStr}
CREATE
(baseNode)-[:ELEMENT_OF]->(baseNode)
MERGE
(ePerson)-[:MEMBER_OF]->(baseNode)
` :
queryStr;
queryStr = `
${queryStr}
RETURN {
pbotID: baseNode.pbotID
}
`;
console.log(queryStr);
const result = await session.run(queryStr);
return result;
}
const isDuplicate = async (session, actionType, nodeType, data) => {
console.log("checkDuplicate")
if ("delete" === actionType || "CharacterInstance" === nodeType) {
return { value: false };
}
let query = '';
let error = '';
if (["Reference", "Schema"].includes(nodeType)) {
query = `MATCH (n:${nodeType} {title: "${data.title}"})`;
error = `${nodeType} with same title found`
} else if (["OTU", "Specimen", "Description", "Collection", "Group"].includes(nodeType)) {
query = `MATCH (n:${nodeType} {name: ${JSON.stringify(data.name)}})`;
error = `${nodeType} with same name found`
} else if ("Person" === nodeType) {
query = `MATCH (n:${nodeType} {surname: "${data.surname}", given: "${data.given}" ${data.middle ? `, middle: "${data.middle}"` : '' }})`;
error = `${nodeType} with same name found`
} else if ("Image" === nodeType) {
query = `MATCH (n:${nodeType} {link: "${data.link}"})-[:IMAGE_OF]-(m {pbotID: "${data.imageOf}"})`;
error = `${nodeType} with same link found`
} else if ("Character" === nodeType) {
query = `
MATCH
(n:${nodeType} {name: "${data.name}"})-[:CHARACTER_OF]->(m {pbotID:"${data.parentID}"})
`;
error = `${nodeType} with same name and parent found`
} else if ("State" === nodeType) {
query = `
MATCH
(n:${nodeType} {name: "${data.name}"})-[:STATE_OF]->(m {pbotID:"${data.parentID}"})
`;
error = `${nodeType} with same name and parent found`
/*
} else if ("CharacterInstance" === nodeType) {
//TODO: This does nothing because CharacterInstance create and edit are in schema.graphql. Add dup check logic there.
query = `
MATCH
(s:State {pbotID: "${data.stateID}"})<-[:HAS_STATE]-(n:${nodeType})-[:INSTANCE_OF]->(c:Character {pbotID: "${data.characterID}"})
`;
error = `${nodeType} with same character and state found`
*/
} else if ("Synonym" === nodeType) {
query = `
MATCH
(:OTU {pbotID: "${data.otus[0]}"})<-[:SAME_AS]-(n:${nodeType})-[:SAME_AS]->(:OTU {pbotID: "${data.otus[1]}"}),
(n)-[:SAME_AS]->(o2:OTU)
`;
error = `${nodeType} with same OTUs found`
} else if ("Comment" === nodeType) {
query = `
MATCH
(n:${nodeType} {content: "${data.content}"})-[:REFERS_TO]->(m {pbotID:"${data.subjectID}"})
`;
error = `${nodeType} with same content found`
} else {
error = `Unrecognized node type: ${nodeType}`
}
if ("update" === actionType) {
query = `${query} WHERE n.pbotID <> "${data.pbotID}"`;
}
query = `${query} RETURN n`;
console.log("dup query = ")
console.log(query)
const result = await session.run(query);
return {
value: result.records.length > 0,
msg: error
}
}
const mutateNode = async (context, nodeType, data, type) => {
const driver = context.driver;
const session = driver.session()
console.log("mutateNode");
console.log(data);
try {
const dup = await isDuplicate(session, type, nodeType, data);
if (dup.value) {
throw new ValidationError(dup.msg);
}
//TODO: this is all to get public group ID. Should probably get this once on boot.
const queryStr = `
MATCH
(g:Group {name:"public"})
RETURN
g
`;
const pgResult = await session.run(
queryStr
);
const publicGroupID = pgResult.records.length > 0 ? pgResult.records[0].get(0).properties.pbotID : null;
if (data.references) {
const testSet = new Set();
data.references.forEach(ref => {
testSet.add(ref.pbotID);
});
if (testSet.size < data.references.length) {
throw new ValidationError(`Cannot not have duplicate references`);
}
}
if ("Person" !== nodeType && data.groups && data.groups.includes(publicGroupID) && data.groups.length > 1) {
throw new ValidationError(`A public ${nodeType} cannot be in other groups.`);
}
if ("OTU" === nodeType) {
data.typeSpecimens.forEach(specimen => {
if (!data.identifiedSpecimens.includes(specimen)) {
throw new ValidationError(`Type specimens must also be identified specimens`);
}
})
if (data.holotypeSpecimen) {
if (!data.typeSpecimens.includes(data.holotypeSpecimen)) {
throw new ValidationError(`Holotype must also be a type specimen`);
}
if (data.groups.includes(publicGroupID)) {
const pubHolo = await isPublic(session, data.holotypeSpecimen);
if (!pubHolo) {
throw new ValidationError(`A holotype specimen for a public OTU must also be public`);
}
}
}
}
const result = await session.writeTransaction(async tx => {
let result;
switch (type) {
case "create":
if ("Person" === nodeType) {
if (data.orcid && !new RegExp(/https:\/\/orcid.org\/\d{4}-\d{4}-\d{4}-\d{4}/).test(data.orcid)) {
throw new ValidationError(`orcid (${data.orcid}) is not valid format`);
}
//All people are created public
data.groups = [publicGroupID];
//Stub in reason/bio to prevent undefined error
data.reason = data.reason ? data.reason : null;
data.bio = data.bio ? data.bio : null;
//Check if person already exists
const person = await getPerson(tx, data.email);
console.log("Person:");
console.log(person);
if (person) {
console.log("person already exists");
throw new ValidationError(`${nodeType} with that email already exists`);
}
} else if ("Collection" === nodeType) {
if (!data.location) {
if (data.lat && data.lon) {
data.location = {
latitude: data.lat,
longitude: data.lon
}
} else {
throw new ValidationError(`${nodeType} mutation must have either location or lat/lon`);
}
}
data.lon = null;
data.lat = null;
} else if ("Synonym" === nodeType) {
if (await isSynonym(tx, data.otus)) {
throw new ValidationError(`${nodeType} already exists`);
}
} else if ("Character" === nodeType || "State" === nodeType || "CharacterInstance" === nodeType || "Specimen" === nodeType || "Image" === nodeType) {
console.log("++++++++++++++++++++++fetching groups++++++++++++++++++");
//fetch groups from root and put in data
const groups = await getGroups(tx, data);
console.log("Groups:");
console.log(groups);
data["groups"] = groups;
}
result = await handleCreate(
tx,
nodeType,
data
);
break;
case "update":
console.log("Updating");
let doGroupCascade = true;
if ("Person" === nodeType) {
if (data.orcid && !new RegExp(/https:\/\/orcid.org\/\d{4}-\d{4}-\d{4}-\d{4}/).test(data.orcid)) {
throw new ValidationError(`orcid (${data.orcid}) is not valid format`);
}
//Stub in reason/bio to prevent undefined error
data.reason = data.reason ? data.reason : null;
data.bio = data.bio ? data.bio : null;
//All people are public
if (data.groups) {
if (!data.groups.includes(publicGroupID)) {
data.groups.push(publicGroupID);
}
} else {
data.groups = [publicGroupID];
}
//Check if person already exists
const person = await getPerson(tx, data.email);
if (person && person.properties.pbotID !== data.pbotID) {
console.log("person already exists");
throw new ValidationError(`${nodeType} with that email already exists`);
}
if (person) {
if (person.properties.password && person.properties.pbotID !== data.enteredByPersonID) {
console.log("attempt to edit registered user");
throw new ValidationError(`Cannot edit registered users other than yourself`);
} else if (person.properties.pbotID !== data.pbotID) {
console.log("person already exists");
throw new ValidationError(`${nodeType} with that email already exists`);
}
}
} else if ("Collection" === nodeType) {
if (!data.location) {
if (data.lat && data.lon) {
data.location = {
latitude: data.lat,
longitude: data.lon
}
} else {
throw new ValidationError(`${nodeType} mutation must have either location or lat/lon`);
}
}
data.lon = null;
data.lat = null;
} else if (("Character" === nodeType || "State" === nodeType || "Specimen" === nodeType || "Image" === nodeType) && !data.groupCascade) {
console.log("++++++++++++++++++++++fetching groups++++++++++++++++++");
//fetch groups from Schema and put in data
const groups = await getGroups(tx, data);
console.log("Groups:");
console.log(groups);
data["groups"] = groups;
//For Characters/States, we are moving them to a new parent within same Schema. For Specimens, there is no cascade.
//Groups are not changing so no need to cascade.
doGroupCascade = false;
}
//Prevent privatization of public nodes
if (await isPublic(tx, data.pbotID) && !data.groups.includes(publicGroupID)) {
throw new ValidationError(`This ${nodeType} is public. Cannot change groups`);
}
//TODO: If setting to newly public, clean out old DELETE data
if (doGroupCascade) {
const groupCascadeRelationships = schemaDeleteMap[nodeType].cascadeRelationships || [];
const remoteNodes = await getRelationships(
tx,
data.pbotID,
groupCascadeRelationships,
data.enteredByPersonID,
nodeType
);
//console.log("remoteNodes");
//console.log(remoteNodes);
console.log("cascading groups");
await Promise.all(remoteNodes.map(node => {
node.groups = data.groups;
node.groupCascade = true;
node.enteredByPersonID = data.enteredByPersonID;
console.log("node after");
console.log(node);
return mutateNode(context, node.nodeType, node, "update")
})).catch(error => {
console.log(error);
throw new ValidationError(`Unable to cascade groups for ${nodeType}`);
});
}
result = await handleUpdate(
tx,
nodeType,
data
);
break;
case "delete":
const pbotID = data.pbotID;
const enteredByPersonID = data.enteredByPersonID;
const cascade = data.cascade || false;
console.log(cascade ?
schemaDeleteMap[nodeType].blockingRelationships :
[...schemaDeleteMap[nodeType].blockingRelationships, ...schemaDeleteMap[nodeType].cascadeRelationships]);
const blockingRelationships = await getRelationships(
tx,
pbotID,
cascade ?
schemaDeleteMap[nodeType].blockingRelationships :
[...schemaDeleteMap[nodeType].blockingRelationships, ...schemaDeleteMap[nodeType].cascadeRelationships],
enteredByPersonID,
nodeType
);
if (blockingRelationships.length > 0) {
console.log("cannot delete");
throw new ValidationError(`${nodeType} has blocking relationships`);
} else {
if (cascade) {
const remoteNodes = await getRelationships(
tx,
pbotID,
schemaDeleteMap[nodeType].cascadeRelationships
);
console.log("remoteNodes");
console.log(remoteNodes);
await Promise.all(remoteNodes.map(node => {
console.log(node);
return mutateNode(context, node.nodeType, {pbotID: node.pbotID, enteredByPersonID: enteredByPersonID, cascade: cascade}, "delete")
})).catch(error => {
console.log(error);
throw new ValidationError(`Unable to cascade delete ${nodeType}`);
});
}
//If this is a Group node, pass both blocking and nonblocking, since
//we want to ignore the last ELEMENT_OF and MEMBER_OF
result = await handleDelete(
tx,
nodeType,
pbotID,
enteredByPersonID,
"Group" === nodeType ?
[...schemaDeleteMap[nodeType].nonblockingRelationships,
...schemaDeleteMap[nodeType].blockingRelationships] :
schemaDeleteMap[nodeType].nonblockingRelationships
);
}
break;
default:
throw new Exception("Invalid mutation type");
}
console.log("result");
console.log(result);
return result.records[0]._fields[0];
});
return result;
} finally {
await session.close();
}
}
// Validation functions for checking latitude/longitude
//Based on https://www.apollographql.com/docs/apollo-server/schema/custom-scalars/
function latValue(value) {
if (typeof value === 'number' && value >= -90 && value <= 90) {
return value;
}
throw new GraphQLError(
`Provided value (${value}, ${typeof value}) is not avalid latitude`,
{
extensions: { code: 'BAD_USER_INPUT' },
}
);
}
function lonValue(value) {
if (typeof value === 'number' && value >= -180 && value <= 180) {
return value;
}
throw new GraphQLError(
`Provided value (${value}, ${typeof value}) is not a valid longitude`,
{
extensions: { code: 'BAD_USER_INPUT' },
}
);
}
export const Resolvers = {
Latitude: new GraphQLScalarType({
name: 'Latitude',
description: 'Latitude custom scalar type',
parseValue: latValue,
serialize: latValue,
parseLiteral(ast) {
if (ast.kind === Kind.FLOAT) {
return latValue(parseFloat(ast.value));
}
throw new GraphQLError('Provided value is not a valid latitude', {
extensions: { code: 'BAD_USER_INPUT' },
});
},
}),
Query: {
echoLat(_, { lat }) {
return lat;
},
},
Longitude: new GraphQLScalarType({
name: 'Longitude',
description: 'Longitude custom scalar type',
parseValue: lonValue,
serialize: lonValue,
parseLiteral(ast) {
if (ast.kind === Kind.FLOAT) {
return lonValue(parseFloat(ast.value));
}
throw new GraphQLError('Provided value is not a valid longitude', {
extensions: { code: 'BAD_USER_INPUT' },
});
},
}),
Query: {
echoLon(_, { lon }) {
return lon;
},
},
Upload: GraphQLUpload,
Person: {
email: (parent, args, context, info) => {
return context.user.password ?
parent.email :
null;