-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.js
1401 lines (1125 loc) · 38.2 KB
/
graph.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
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
const path = require('path')
const JSON5 = require('json5')
const yaml = require('js-yaml')
const fsPromises = require('fs/promises')
const schema = require("./schema.js")
const web = require("./web.js")
const timers = require('timers-promises')
// some layouts are same for all users
const COMMON_LAYOUTS = ['schema', 'navigation', 'about']
const MAX_STR_LENGTH = 2048
const MATCH_BY_ID = true
// Assigning to exports will not modify module, must use module.exports
module.exports = class Graph {
async initDB(docIndex) {
console.log(`ArcadeDB: ${web.getURL()}`)
console.log(`Checking database...`)
this.docIndex = docIndex
const query = 'MATCH (n:Schema) return n'
try {
await web.cypher(query)
} catch (e) {
try {
if(e.code == 'ERR_GOT_REQUEST_ERROR') {
console.log('Request error! Check database. Did you set DB_PASSWORD? exiting...')
process.exit(1)
}
if(e.code == 'ECONNREFUSED') {
console.log('database not ready, waiting 10 seconds...')
await timers.setTimeout(10000)
}
console.log('Checking database...')
var result = await web.cypher(query)
} catch (e) {
if(e.code == 'ECONNREFUSED') {
console.log(`ERROR: Database connection refused! \nIs Arcadedb running at ${web.getURL()}?`)
console.log('exiting...')
process.exit(1)
} else {
console.log(`Database not found! \nTrying to create in 10 secs...`)
await timers.setTimeout(10000)
try {
await web.createDB()
} catch (e) {
console.log(`Could not init database. \nIs Arcadedb running at ${web.getURL()}?`)
console.log('exiting...')
process.exit(1)
}
}
}
}
await this.setSystemNodes()
}
async setSystemNodes() {
try {
// database exist, make sure that some base types are present
await web.createVertexType('Schema')
await web.createVertexType('Person')
await web.createVertexType('UserGroup')
await web.createVertexType('Menu')
await web.createVertexType('Query')
await web.createVertexType('Tag')
await schema.importSystemSchema()
await this.createSystemGraph()
// Make sure that base system graph exists
} catch(e) {
console.log(e)
console.log(`Could not init system, exiting...`)
process.exit(1)
}
}
async createSystemGraph() {
try {
// Usergroup "Basic"
var query = 'MERGE (m:UserGroup {id:"user"}) SET m.label = "User", m._active = true RETURN m'
var group = await web.cypher(query)
// Menu "Me"
// var query = 'MERGE (m:Menu {id:"me"}) SET m.label = "Me", m._active = true RETURN m'
// var menu = await web.cypher(query)
// Make sure that "Me" menu is linked to the "User" group
// query = `MATCH (m:Menu), (g:UserGroup) WHERE id(m) = "${menu.result[0]['@rid']}" AND id(g) = "${group.result[0]['@rid']}" MERGE (m)-[:VISIBLE_FOR_GROUP]->(g)`
// await web.cypher(query)
// default local user
query = `MERGE (p:Person {id:"local.user@localhost"}) SET p._group = "user", p._access = "admin", p._active = true, p.label = "Local You", p.description = "It's really You!" RETURN p`
await web.cypher(query)
} catch (e) {
console.log(query)
throw('System graph creation failed')
}
}
async createIndex() {
console.log('Starting to index with flexsearch ...')
var query = 'MATCH (n) return id(n) as id, n.label as label, n.description as description'
try {
var result = await web.cypher( query)
try {
for (var node of result.result) {
await this.docIndex.add(node)
}
console.log('Indexing done')
} catch(e) {
// if indexing fails, then we have a problem and we quit
console.log('Indexing failed, exiting...')
console.log(e)
process.exit(1)
}
} catch(e) {
console.log(`Could not find database. \nIs Arcadedb running at ${URL}?`)
process.exit(1)
}
}
async query(body) {
return web.cypher( body.query)
}
async hasAdminPermissions(auth_header) {
var me = await this.myId(auth_header)
if(me.access === 'admin') {
return true
}
return false
}
async hasCreatePermissions(type_data, auth_header) {
var me = await this.myId(auth_header)
if(me.access === 'admin') {
return true
} else if(me.access === 'creator' && type_data.label !== 'Schema') {
return true
} else if(me.access === 'user' && type_data._public) {
return true
}
return false
}
async hasDeletePermissions(auth_header) {
var me = await this.myId(auth_header)
if(me.access === 'admin') {
return true
} else return false
}
async hasConnectPermissions(from, to, auth_header) {
var me = await this.myId(auth_header)
from = this.checkHastag(from)
to = this.checkHastag(to)
// one can join oneself
if(me.rid === from || me.rid === to)
return true
if(me.access === 'creator' || me.access === 'admin') {
return true
}
// TODO: this must check that Schema can be connected only by admin
return false
}
async hasNodeAttributePermissions(node_rid, auth_header) {
var me = await this.myId(auth_header)
node_rid = this.checkHastag(node_rid)
// one can set one's own attributes
if(me.rid === node_rid)
return true
if(me.access === 'admin') {
return true
}
return false
}
async hasEdgeAttributePermissions(from, to, auth_header) {
var me = await this.myId(auth_header)
from = this.checkHastag(from)
to = this.checkHastag(to)
if(me.rid === from || me.rid === to)
return true
if(me.access === 'creator' || me.access === 'admin') {
return true
}
return false
}
async create(type, data, auth_header) {
try {
console.log(data)
let type_attributes = {}
if(type === 'Schema') {
type_attributes.label = 'Schema'
} else {
type_attributes = await schema.getSchemaType(type, 1)
}
console.log(type_attributes)
const privileged = await this.hasCreatePermissions(type_attributes, auth_header)
if(!privileged) {
throw(`no rights to add "${type}"`)
}
var data_str_arr = []
// expression data to string
for(var key in data) {
if(data[key]) {
if(Array.isArray(data[key]) && data[key].length > 0) {
if(!key.includes('@')) {
data[key] = data[key].map(i => `'${i}'`).join(',')
data_str_arr.push(`${key}:[${data[key]}]`)
}
} else if (typeof data[key] == 'string') {
if(data[key].length > MAX_STR_LENGTH) throw('Too long data!')
if(!key.includes('@')) {
data_str_arr.push(`${key}:"${data[key].replace(/"/g, '\\"')}"`)
}
} else {
data_str_arr.push(`${key}:${data[key]}`)
}
}
}
// set some system attributes to all Persons
if(type === 'Person') {
if(!data['_group']) data_str_arr.push(`_group: "user"`) // default user group for all persons
if(!data['_access']) data_str_arr.push(`_access: "user"`) // default access for all persons
}
// _active
if(!data['_active']) data_str_arr.push(`_active: true`)
var query = `CREATE (n:${type} {${data_str_arr.join(',')}}) return n`
console.log(query)
return web.cypher( query)
} catch(e) {
console.log(e)
throw('Creation failed ' + e)
}
}
async deleteNode(rid, auth_header) {
try {
if(await this.hasDeletePermissions(auth_header)) {
rid = this.checkHastag(rid)
var query = `MATCH (n) WHERE id(n) = '${rid}' RETURN labels(n) as type`
var response = await web.cypher(query)
if(response.result && response.result.length == 1) {
var type = response.result[0].type
var query_delete = `DELETE FROM ${type} WHERE @rid = "${rid}"`
console.log(query_delete)
return web.sql(query_delete)
}
}
return response
} catch (e) {
console.log(e)
throw('Node delete failed ' + e)
}
}
async merge(type, node) {
var attributes = []
for(var key of Object.keys(node[type])) {
attributes.push(`s.${key} = "${node[type][key]}"`)
}
// set some system attributes to all Persons
if(type === 'Person') {
if(!node['_group']) attributes.push(`s._group = "user"`) // default user group for all persons
if(!node['_access']) attributes.push(`s._access = "user"`) // default access for all persons
}
// _active
attributes.push(`s._active = true`)
// merge only if there is ID for node
if('id' in node[type]) {
var insert = `MERGE (s:${type} {id:"${node[type].id}"}) SET ${attributes.join(',')} RETURN s`
try {
var response = await web.cypher( insert)
console.log(response)
this.docIndex.add({id: response.result[0]['@rid'],label:node.label})
return response.data
} catch (e) {
try {
await web.createVertexType(type)
var response = await web.cypher( insert)
console.log(response)
this.docIndex.add({id: response.result[0]['@rid'],label:node.label})
return response.data
} catch(e) {
console.log(e)
throw('Merge failed!')
}
}
}
}
// TODO
async mergeConnect(edge) {
// NOTE: we cannnot use Cypher's merge, since it includes attributes in comparision
// TODO: Currently we do not update attributes for existing links
if(edge.from && edge.to && edge.relation) {
try {
const query = `MATCH (from)-[:${edge.relation}]->(to) WHERE from.id = "${edge.from}" AND to.id = "${edge.to}" RETURN from, to`
var response = await web.cypher(query)
// if relation is not found, create it
if(response.result.length === 0) {
return await this.connect(edge.from, edge.relation, edge.to, MATCH_BY_ID, edge.attributes)
}
} catch(e) {
console.log(e)
throw('Merge connection failed!')
}
} else {
throw('Edge is not comple!\n' + edge)
}
}
async getEdgeTargets(edge_rid) {
edge_rid = this.checkHastag(edge_rid)
const query = `MATCH (from)-[r]->(to) WHERE id(r) = "${edge_rid}" RETURN from, to`
var response = await web.cypher( query)
if(response.result.length > 0) {
var data = {from: response.result[0].from['@rid'], to: response.result[0].to['@rid']}
return data
} else {
throw(`Edge not found: ${edge_rid}`)
}
}
checkHastag(rid) {
if(!rid.match(/^#/)) rid = '#' + rid
return rid
}
// data = {from:[RID] ,relation: '', to: [RID]}
async connect(from, relation, to, match_by_id, attributes, auth_header) {
console.log('Connectiong vertices...')
try {
if(await this.hasConnectPermissions(from, to, auth_header)) {
var attributes_str = ''
var relation_type = ''
if(!match_by_id) {
from = this.checkHastag(from)
to = this.checkHastag(to)
}
const permissions = await this.hasConnectPermissions(from, to, auth_header)
if(typeof relation == 'object') {
relation_type = relation.type
if(relation.attributes)
attributes_str = this.createAttributeCypher(relation.attributes)
} else if (typeof relation == 'string') {
relation_type = relation
}
if(attributes) attributes_str = this.createAttributeCypher(attributes)
console.log(attributes_str)
// when we link normally, we use RID
var query = `MATCH (from), (to) WHERE id(from) = "${from}" AND id(to) = "${to}" CREATE (from)-[r:${relation_type} ${attributes_str}]->(to) RETURN from, r, to`
// when we import stuff, then we connect by id
if(match_by_id) {
query = `MATCH (from), (to) WHERE from.id = "${from}" AND to.id = "${to}" CREATE (from)-[r:${relation_type} ${attributes_str}]->(to) RETURN from, r, to`
}
return web.cypher( query)
}
} catch (e) {
console.log(e)
throw('Connection creation failed ')
}
}
// delete edge based on edge type and source and target RIDs
async unconnect(data) {
try {
data.from = this.checkHastag(data.from)
data.to = this.checkHastag(data.to)
var query = `MATCH (from)-[r:${data.rel_type}]->(to) WHERE id(from) = "${data.from}" AND id(to) = "${data.to}" DELETE r RETURN from`
return web.cypher( query)
} catch(e) {
console.log(e)
throw('Connection removal failed ')
}
}
// delete edge based on edge RID
async deleteEdge(rid, auth_header) {
try {
var targets = await this.getEdgeTargets(rid)
if(await this.hasConnectPermissions(targets.from, targets.to, auth_header)) {
rid = this.checkHastag(rid)
var query = `MATCH (from)-[r]->(to) WHERE id(r) = '${rid}' DELETE r`
return web.cypher( query)
} else {
throw('No rights to delete edge')
}
} catch(e) {
console.log(e)
throw('Deleting edge failed ')
}
}
async setEdgeAttribute(rid, data, auth_header) {
try {
var targets = await this.getEdgeTargets(rid)
if(this.hasEdgeAttributePermissions(targets.from, targets.to, auth_header)) {
rid = this.checkHastag(rid)
let query = `MATCH (from)-[r]->(to) WHERE id(r) = '${rid}' `
if(Array.isArray(data.value)) {
if(data.value.length > 0) {
data.value = data.value.map(i => `'${i}'`).join(',')
query = query + `SET r.${data.name} = [${data.value}]`
} else {
query = query + `SET r.${data.name} = []`
}
} else if(typeof data.value == 'boolean' || typeof data.value == 'number') {
query = query + `SET r.${data.name} = ${data.value}`
} else if(typeof data.value == 'string') {
query = query + `SET r.${data.name} = '${data.value.replace(/'/g,"\\'")}'`
}
return web.cypher( query)
} else {
throw('No rights to set edge attributes')
}
} catch(e) {
console.log(e)
throw('Edge attribut setting failed ' + e)
}
}
async setNodeAttribute(rid, data, auth_header) {
try {
if(this.hasNodeAttributePermissions(rid, auth_header)) {
rid = this.checkHastag(rid)
let query = `MATCH (node) WHERE id(node) = '${rid}' `
if(Array.isArray(data.value) && data.value.length > 0) {
data.value = data.value.map(i => `'${i}'`).join(',')
query = `SET node.${data.key} = [${data.value}]`
} else if(typeof data.value == 'boolean') {
query = query + `SET node.${data.key} = ${data.value}`
} else if(typeof data.value == 'string') {
query = query + `SET node.${data.key} = '${data.value.replace(/'/g,"\\'")}'`
}
return web.cypher( query)
} else {
throw('No rights to set node attributes')
}
} catch(e) {
console.log(e)
throw('Node attribute setting failed ' + e)
}
}
async getNodeAttributes(rid) {
rid = this.checkHastag(rid)
var query = `MATCH (node) WHERE id(node) = '${rid}' RETURN node`
return web.cypher( query)
}
async getGraph(query, ctx) {
var me = await this.myId(ctx.request.headers.mail)
// ME
if(query.includes('_ME_')) {
query = query.replace('_ME_', me.rid)
}
var schema_relations = null
// get schemas first so that one can map relations to labels
if(!body.raw) {
schema_relations = await this.getSchemaRelations()
}
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations,
current: body.current,
me: me
}
return web.cypher( body.query, options)
}
async getGraphByNode(body, ctx) {
var me = await this.myId(ctx.request.headers.mail)
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations,
current: body.current,
me: me
}
const query = `MATCH (p) WHERE id(p) = "#${body.current}" OPTIONAL MATCH (p)-[r]-(t) RETURN p,r,t`
return web.cypher(query, options)
}
async getGraphByRelation(body, ctx) {
var me = await this.myId(ctx.request.headers.mail)
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations,
current: body.current,
me: me
}
const query = `MATCH (p) WHERE id(p) = "${body.current}" OPTIONAL MATCH (p)-[r:${body.relation}]-(t) RETURN p,r,t`
return web.cypher(query, options)
}
async getGraphNavigation(body, ctx) {
var me = await this.myId(ctx.request.headers.mail)
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations,
me: me
}
const query = `match (s) WHERE s:Query OR s:Menu OR s:UserGroup OPTIONAL MATCH (s)-[r]-(p) OPTIONAL MATCH (p)-[r2]-(group) return s,p, r, group, r2`
return web.cypher(query, options)
}
async getGraphByQueryRID(body, ctx) {
var me = await this.myId(ctx.request.headers.mail)
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations,
me: me
}
const query = `MATCH (query:Query) WHERE id(query) = "#${body.rid}" RETURN query`
var response = await web.cypher(query)
if(response.result && response.result.length == 1) {
return web.cypher(response.result[0].query, options)
}
}
// currently used only for getting items on map
async getLinkedByNode(body, ctx) {
var me = await this.myId(ctx.request.headers.mail)
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations,
me: me
}
const query = `MATCH (node)-[r]->(current:${body.type}) WHERE id(current) = "#${body.current}" RETURN node`
return web.cypher(query, options)
}
// currently not used (meant for several nodes display)
async getGraphByItemList(body, ctx) {
const items_str = body.items.map(x => `'#${x}'`).join(',')
var me = await this.myId(ctx.request.headers.mail)
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations,
me: me
}
const query = `MATCH (p) WHERE id(p) IN [${items_str}] OPTIONAL MATCH (p)-[r]-(p2) WHERE id(p2) IN [${items_str}] RETURN p, r, p2`
return web.cypher(query, options)
}
// for stories
async getGraphByItemListRaw(body, ctx) {
const items_str = body.items.map(x => `'${x}'`).join(',')
var me = await this.myId(ctx.request.headers.mail)
var schema_relations = null
const options = {
serializer: 'graph',
format: 'cytoscape',
me: me
}
const query = `MATCH (p) WHERE id(p) IN [${items_str}] RETURN p`
return web.cypher(query, options)
}
async getSchemaGraph() {
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations
}
const query = `MATCH (s:Schema) WHERE NOT s._type IN ["Menu", "Query", "UserGroup", "Tag", "NodeGroup"] OPTIONAL MATCH (s)-[r]-(s2:Schema) return s,r,s2`
return await web.cypher(query, options)
}
async getSchemaGraphByTag(tag) {
var schema_relations = null
// get schemas first so that one can map relations to labels
schema_relations = await this.getSchemaRelations()
const options = {
serializer: 'graph',
format: 'cytoscape',
schemas: schema_relations
}
const query =
`MATCH (s:Schema)-[r]-(s2:Schema) WHERE NOT s._type IN ["Menu", "Query", "UserGroup", "Tag", "NodeGroup"] AND "${tag}" IN r.tags return s,r,s2`
return await web.cypher(query, options)
}
async getMapPositions(body, ctx) {
const query = 'MATCH (n)-[r]-(map:QueryMap) RETURN r.x as x, r.y as y, id(n) as id'
return web.cypher(query)
}
async getSchemaRelations() {
var schema_relations = {}
var schemas = await web.cypher( 'MATCH (s:Schema)-[r]->(s2:Schema) return type(r) as type, r.label as label, r.label_rev as label_rev, COALESCE(r.label_inactive, r.label) as label_inactive, s._type as from, s2._type as to, r.tags as tags, r.compound as compound')
schemas.result.forEach(x => {
schema_relations[`${x.from}:${x.type}:${x.to}`] = x
})
return schema_relations
}
async getSearchData(search) {
if(search[0]) {
var arr = search[0].result.map(x => '"' + x + '"')
var query = `MATCH (n) WHERE id(n) in [${arr.join(',')}] AND NOT n:Schema return id(n) as id, n.label as label, labels(n) as type LIMIT 10`
return web.cypher( query)
} else {
return {result:[]}
}
}
checkRelationData(data) {
if(data.from) {
data.from = this.checkHastag(data.from)
}
if(data.to) {
if(!data.to.match(/^#/)) data.to = '#' + data.to
}
if(data.relation_id) {
if(!data.relation_id.match(/^#/)) data.relation_id = '#' + data.relation_id
}
return data
}
createAttributeCypher(attributes) {
var attrs = []
var cypher = ''
for (var key in attributes) {
console.log(key)
console.log('.............')
if(Array.isArray(attributes[key])) {
if(attributes[key].length > 0) {
var values_str = attributes[key].map(i => `'${i}'`).join(',')
attrs.push(`${key}:[${values_str}]`)
} else {
attrs.push(`${key}:[]`)
}
} else {
attrs.push(`${key}: "${attributes[key]}"`)
}
}
return '{' + attrs.join(',') + '}'
}
async checkMe(user, access) {
var rights = 'user'
if(['user', 'creator', 'admin'].includes(access)) rights = access
if(!user) throw('user not defined')
var query = `MATCH (me:Person {id:"${user}"}) return id(me) as rid, me._group as group, me._access as access`
var result = await web.cypher(query)
// add user if not found
if(result.result.length == 0) {
query = `MERGE (p:Person {id: "${user}"}) SET p.label = "${user}", p._group = 'user', p._active = true, p._access = '${rights}'`
result = await web.cypher(query)
query = `MATCH (me:Person {id:"${user}"}) return id(me) as rid, me._group as group`
result = await web.cypher(query)
return result.result[0]
} else return result.result[0]
}
async myId(user) {
if(!user) throw('user not defined')
var query = `MATCH (me:Person {id:"${user}"}) return id(me) as rid, me._group as group, me._access as access`
var response = await web.cypher(query)
if(!response.result) throw('user not found!')
return response.result[0]
}
async getGroups() {
var query = 'MATCH (x:UserGroup) RETURN x.label as label, x.id as id'
var result = await web.cypher( query)
return result.result
}
async getMaps() {
var query = 'MATCH (t:QueryMap) RETURN t order by t.label'
var result = await web.cypher( query)
return result.result
}
async getMapData(rid) {
if(!rid.match(/^#/)) rid = '#' + rid
var query = `MATCH (map:QueryMap) WHERE id(map) = "${rid}" RETURN map.image as image, map.scale as scale`
var response = await web.cypher( query)
if(response.result && response.result.length == 1)
return response.result[0]
else
return {}
}
async getMenus(group) {
//var query = 'MATCH (m:Menu) return m'
var query = `MATCH (m:Menu) -[:VISIBLE_FOR_GROUP]->(n:UserGroup {id:"${group}"}) OPTIONAL MATCH (m)<-[r]-(q) WHERE (q:Query OR q:Tag) AND NOT exists(r._active) OR NOT r._active = false RETURN COLLECT(DISTINCT q) AS items, m.label as label, m.id as id ORDER BY id`
console.log(query)
var result = await web.cypher( query)
var menus = this.forceArray(result.result, 'items')
return menus
}
forceArray(data, property) {
for(var row of data) {
if(!Array.isArray(row[property])) {
row[property] = [row[property]]
}
}
return data
}
// data = {rel_types:[], node_types: []}
async myGraph(user, data) {
if(!data.return) data.return = 'p,r,n, n2'
var rel_types = []; var node_types = []
var node_query = ''
if(!user || !Array.isArray(data.rel_types) || !Array.isArray(data.node_types)) throw('invalid query!')
// by default get all relations and all nodes linked to 'user'
for(var type of data.rel_types) {
rel_types.push(`:${type.trim()}`)
}
for(var node of data.node_types) {
node_types.push(`n:${node.trim()}`)
}
if(node_types.length) node_query = ` WHERE ${node_types.join (' OR ')}`
var query = `MATCH (p:Person {id:"${user}"})-[r${rel_types.join('|')}]-(n) OPTIONAL MATCH (n)--(n2) ${node_query} return ${data.return}`
return web.cypher( query, 'graph')
}
// get list of documents WITHOUT certain relation
// NOTE: open cypher bundled with Arcadedb did not work with "MATCH NOT (n)-[]-()"" -format. This could be done with other query language.
async getListByType(query_params) {
var query = `MATCH (n) return n.label as text, id(n) as value ORDER by text`
if(query_params.type) query = `MATCH (n:${query_params.type}) return n.label as text, id(n) as value ORDER by text`
var all = await web.cypher( query)
if(query_params.relation && query_params.target) {
query = `MATCH (n:${query_params.type})-[r:${query_params.relation}]-(t) WHERE id(t) = "#${query_params.target}" return COLLECT(id(n)) as ids`
var linked = await web.cypher( query)
//console.log(linked.result)
//console.log(all.result)
var r = all.result.filter(item => !linked.result[0].ids.includes(item.value));
//console.log(r)
return r
} else {
return all
}
}
async getStory(rid) {
if(!rid.match(/^#/)) rid = '#' + rid
var query = `MATCH (s:Story) WHERE id(s) = '${rid}' RETURN s`
var result = await web.cypher( query)
if(result.result.length == 1) {
var filename = 'story_' + rid + '.yaml'
try {
const file_path = path.resolve('./stories', filename)
const data = await fsPromises.readFile(file_path, 'utf8')
const story_data = yaml.load(data)
return story_data
} catch (e) {
throw(e)
}
} else {
throw('Not found')
}
}
async importGraphYAML(filename, mode, auth_header) {
console.log(`** importing graph ${filename} with mode ${mode} **`)
try {
const file_path = path.resolve('./graph', filename)
const data = await fsPromises.readFile(file_path, 'utf8')
const graph_data = yaml.load(data)
const admin = await this.hasAdminPermissions(auth_header)
if(admin) {
if(mode == 'clear') {
await web.clearGraph()
await this.setSystemNodes()
await this.createSystemGraph()
await this.writeGraphToDB(graph_data, auth_header)
} else {
// otherwise we merge
await this.mergeGraphToDB(graph_data)
}
this.createIndex()
}
} catch (e) {
throw(e)
}
console.log('Done import')
}
async mergeGraphToDB(graph) {
try {
for(var node of graph.nodes) {
const type = Object.keys(node)[0]
await this.merge(type, node)
}
for(var edge of graph.edges) {
if(edge.Edge) await this.mergeConnect(edge.Edge)
}
} catch (e) {
throw(e)
}
}
async writeGraphToDB(graph, auth_header) {
try {
for(var node of graph.nodes) {
const type = Object.keys(node)[0]
await this.create(type, node[type], auth_header)
}
for(var edge of graph.edges) {
// edges object format
if(edge.Edge) {
await this.connect(edge.Edge.from, edge.Edge.relation, edge.Edge.to, true, edge.Edge.attributes, auth_header)
// edges string format
} else {
const edge_key = Object.keys(edge)[0]
const splitted = edge_key.split('->')
if(splitted.length == 3) {
const link = splitted[1].trim()
const [from_type, ...from_rest]= splitted[0].split(':')
const [to_type, ...to_rest] = splitted[2].split(':')
const from_id = from_rest.join(':').trim()
const to_id = to_rest.join(':').trim()
await this.connect(from_id, link, to_id, true, edge[edge_key], auth_header)
} else {
throw('Graph edge error: ' + Object.keys(edge)[0])
}
}
}
} catch (e) {