-
Notifications
You must be signed in to change notification settings - Fork 1
/
db-controller.js
1769 lines (1729 loc) · 74.1 KB
/
db-controller.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
#!/usr/bin/env node
/**
* This module is used to connect to a mongodb instance and perform the necessary unit actions
* to complete an API action. The implementation is intended to be a RESTful API.
* Known database misteps, like NOT FOUND, should pass a RESTful message downstream.
*
* It is used as middleware and so has access to the http module request and response objects, as well as next()
*
* @author thehabes
*/
import { newID, db } from './database/index.js'
import utils from './utils.js'
const ObjectID = newID
// Handle index actions
const index = function (req, res, next) {
res.json({
status: "connected",
message: "Not sure what to do"
})
}
/**
* Check if an object with the proposed custom _id already exists.
* If so, this is a 409 conflict. It will be detected downstream if we continue one by returning the proposed Slug.
* We can avoid the 409 conflict downstream and return a newly minted ObjectID.toHextString()
* We error out right here with next(createExpressError({"code" : 11000}))
* @param slug_id A proposed _id.
*
*/
const generateSlugId = async function(slug_id="", next){
let slug_return = {"slug_id":"", "code":0}
let slug
if(slug_id){
slug_return.slug_id = slug_id
try {
slug = await db.findOne({"$or":[{"_id": slug_id}, {"__rerum.slug": slug_id}]})
}
catch (error) {
//A DB problem, so we could not check. Assume it's usable and let errors happen downstream.
console.error(error)
//slug_return.code = error.code
}
if(null !== slug){
//This already exist, give the mongodb error code.
slug_return.code = 11000
}
}
return slug_return
}
/**
* Create a new Linked Open Data object in RERUM v1.
* Order the properties to preference @context and @id. Put __rerum and _id last.
* Respond RESTfully
* */
const create = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
let slug = ""
if(req.get("Slug")){
let slug_json = await generateSlugId(req.get("Slug"), next)
if(slug_json.code){
next(createExpressError(slug_json))
return
}
else{
slug = slug_json.slug_id
}
}
const id = ObjectID()
let generatorAgent = getAgentClaim(req, next)
let context = req.body["@context"] ? { "@context": req.body["@context"] } : {}
let provided = JSON.parse(JSON.stringify(req.body))
let rerumProp = { "__rerum": utils.configureRerumOptions(generatorAgent, provided, false, false)["__rerum"] }
rerumProp.__rerum.slug = slug
delete provided["_rerum"]
delete provided["_id"]
delete provided["@id"]
delete provided["id"]
delete provided["@context"]
let newObject = Object.assign(context, { "@id": process.env.RERUM_ID_PREFIX + id }, provided, rerumProp, { "_id": id })
console.log("CREATE")
try {
let result = await db.insertOne(newObject)
res.set(utils.configureWebAnnoHeadersFor(newObject))
res.location(newObject["@id"])
res.status(201)
delete newObject._id
newObject.new_obj_state = JSON.parse(JSON.stringify(newObject))
res.json(newObject)
}
catch (error) {
//MongoServerError from the client has the following properties: index, code, keyPattern, keyValue
next(createExpressError(error))
}
}
/**
* Mark an object as deleted in the database.
* Support /v1/delete/{id}. Note this is not v1/api/delete, that is not possible (XHR does not support DELETE with body)
* Note /v1/delete/{blank} does not route here. It routes to the generic 404.
* Respond RESTfully
*
* The user may be trying to call /delete and pass in the obj in the body. XHR does not support bodies in delete.
* If there is no id parameter, this is a 400
*
* If there is an id parameter, we ignore body, and continue with that id
*
* */
const deleteObj = async function(req, res, next) {
let id
let err = { message: `` }
try {
id = req.params["_id"] ?? parseDocumentID(JSON.parse(JSON.stringify(req.body))["@id"])
} catch(error){
next(createExpressError(error))
}
let agentRequestingDelete = getAgentClaim(req, next)
let originalObject
try {
originalObject = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
} catch (error) {
next(createExpressError(error))
return
}
if (null !== originalObject) {
let safe_original = JSON.parse(JSON.stringify(originalObject))
if (utils.isDeleted(safe_original)) {
err = Object.assign(err, {
message: `The object you are trying to delete is already deleted. ${err.message}`,
status: 403
})
}
else if (utils.isReleased(safe_original)) {
err = Object.assign(err, {
message: `The object you are trying to delete is released. Fork to make changes. ${err.message}`,
status: 403
})
}
else if (!utils.isGenerator(safe_original, agentRequestingDelete)) {
err = Object.assign(err, {
message: `You are not the generating agent for this object and so are not authorized to delete it. ${err.message}`,
status: 401
})
}
if (err.status) {
next(createExpressError(err))
return
}
let preserveID = safe_original["@id"]
let deletedFlag = {} //The __deleted flag is a JSONObject
deletedFlag["object"] = JSON.parse(JSON.stringify(originalObject))
deletedFlag["deletor"] = agentRequestingDelete
deletedFlag["time"] = new Date(Date.now()).toISOString().replace("Z", "")
let deletedObject = {
"@id": preserveID,
"__deleted": deletedFlag,
"_id": id
}
if (healHistoryTree(safe_original)) {
let result
try {
result = await db.replaceOne({ "_id": originalObject["_id"] }, deletedObject)
} catch (error) {
next(createExpressError(error))
return
}
if (result.modifiedCount === 0) {
//result didn't error out, the action was not performed. Sometimes, this is a neutral thing. Sometimes it is indicative of an error.
err.message = "The original object was not replaced with the deleted object in the database."
err.status = 500
next(createExpressError(err))
return
}
//204 to say it is deleted and there is nothing in the body
console.log("Object deleted: " + preserveID);
res.sendStatus(204)
return
}
//Not sure we can get here, as healHistoryTree might throw and error.
err.message = "The history tree for the object being deleted could not be mended."
err.status = 500
next(createExpressError(err))
return
}
err.message = "No object with this id could be found in RERUM. Cannot delete."
err.status = 404
next(createExpressError(err))
}
/**
* Replace some existing object in MongoDB with the JSON object in the request body.
* Order the properties to preference @context and @id. Put __rerum and _id last.
* This also detects an IMPORT situation. If the object @id or id is not from RERUM
* then trigger the internal _import function.
*
* Track History
* Respond RESTfully
* */
const putUpdate = async function (req, res, next) {
let err = { message: `` }
res.set("Content-Type", "application/json; charset=utf-8")
let objectReceived = JSON.parse(JSON.stringify(req.body))
let generatorAgent = getAgentClaim(req, next)
const idReceived = objectReceived["@id"] ?? objectReceived.id
if (idReceived) {
if(!idReceived.includes(process.env.RERUM_ID_PREFIX)){
//This is not a regular update. This object needs to be imported, it isn't in RERUM yet.
return _import(req, res, next)
}
let id = parseDocumentID(idReceived)
let originalObject
try {
originalObject = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
} catch (error) {
next(createExpressError(error))
return
}
if (null === originalObject) {
//This object is not found.
err = Object.assign(err, {
message: `Object not in RERUM even though it has a RERUM URI. Check if it is an authentic RERUM object. ${err.message}`,
status: 404
})
}
else if (utils.isDeleted(originalObject)) {
err = Object.assign(err, {
message: `The object you are trying to update is deleted. ${err.message}`,
status: 403
})
}
else {
id = ObjectID()
let context = objectReceived["@context"] ? { "@context": objectReceived["@context"] } : {}
let rerumProp = { "__rerum": utils.configureRerumOptions(generatorAgent, originalObject, true, false)["__rerum"] }
delete objectReceived["_rerum"]
delete objectReceived["_id"]
delete objectReceived["@id"]
delete objectReceived["@context"]
let newObject = Object.assign(context, { "@id": process.env.RERUM_ID_PREFIX + id }, objectReceived, rerumProp, { "_id": id })
console.log("UPDATE")
try {
let result = await db.insertOne(newObject)
if (alterHistoryNext(originalObject, newObject["@id"])) {
//Success, the original object has been updated.
res.set(utils.configureWebAnnoHeadersFor(newObject))
res.location(newObject["@id"])
res.status(200)
delete newObject._id
newObject.new_obj_state = JSON.parse(JSON.stringify(newObject))
res.json(newObject)
return
}
err = Object.assign(err, {
message: `Unable to alter the history next of the originating object. The history tree may be broken. See ${originalObject["@id"]}. ${err.message}`,
status: 500
})
}
catch (error) {
//WriteError or WriteConcernError
next(createExpressError(error))
return
}
}
}
else {
//The http module will not detect this as a 400 on its own
err = Object.assign(err, {
message: `Object in request body must have an 'id' or '@id' property. ${err.message}`,
status: 400
})
}
next(createExpressError(err))
}
/**
* RERUM was given a PUT update request for an object whose @id was not from the RERUM API.
* This PUT update request is instead considered internally as an "import".
* We will create this object in RERUM, but its @id will be a RERUM URI.
* __rerum.history.previous will point to the origial URI from the @id.
*
* If this functionality were to be offered as its own endpoint, it would be a specialized POST create.
* */
async function _import(req, res, next) {
let err = { message: `` }
res.set("Content-Type", "application/json; charset=utf-8")
let objectReceived = JSON.parse(JSON.stringify(req.body))
let generatorAgent = getAgentClaim(req, next)
const id = ObjectID()
let context = objectReceived["@context"] ? { "@context": objectReceived["@context"] } : {}
let rerumProp = { "__rerum": utils.configureRerumOptions(generatorAgent, objectReceived, false, true)["__rerum"] }
delete objectReceived["_rerum"]
delete objectReceived["_id"]
delete objectReceived["@id"]
delete objectReceived["id"]
delete objectReceived["@context"]
let newObject = Object.assign(context, { "@id": process.env.RERUM_ID_PREFIX + id }, objectReceived, rerumProp, { "_id": id })
console.log("IMPORT")
try {
let result = await db.insertOne(newObject)
res.set(utils.configureWebAnnoHeadersFor(newObject))
res.location(newObject["@id"])
res.status(200)
delete newObject._id
newObject.new_obj_state = JSON.parse(JSON.stringify(newObject))
res.json(newObject)
}
catch (error) {
//MongoServerError from the client has the following properties: index, code, keyPattern, keyValue
next(createExpressError(error))
}
}
/**
* Update some existing object in MongoDB with the JSON object in the request body.
* Note that only keys that exist on the object will be respected. This cannot set or unset keys.
* If there is nothing to PATCH, return a 200 with the object in the response body.
* Order the properties to preference @context and @id. Put __rerum and _id last.
* Track History
* Respond RESTfully
* */
const patchUpdate = async function (req, res, next) {
let err = { message: `` }
res.set("Content-Type", "application/json; charset=utf-8")
let objectReceived = JSON.parse(JSON.stringify(req.body))
let patchedObject = {}
let generatorAgent = getAgentClaim(req, next)
if (objectReceived["@id"]) {
let id = parseDocumentID(objectReceived["@id"])
let originalObject
try {
originalObject = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
} catch (error) {
next(createExpressError(error))
return
}
if (null === originalObject) {
//This object is not in RERUM, they want to import it. Do that automatically.
//updateExternalObject(objectReceived)
err = Object.assign(err, {
message: `This object is not from RERUM and will need imported. This is not automated yet. You can make a new object with create. ${err.message}`,
status: 501
})
}
else if (utils.isDeleted(originalObject)) {
err = Object.assign(err, {
message: `The object you are trying to update is deleted. ${err.message}`,
status: 403
})
}
else {
patchedObject = JSON.parse(JSON.stringify(originalObject))
delete objectReceived.__rerum //can't patch this
delete objectReceived._id //can't patch this
delete objectReceived["@id"] //can't patch this
//A patch only alters existing keys. Remove non-existent keys from the object received in the request body.
for (let k in objectReceived) {
if (originalObject.hasOwnProperty(k)) {
if (objectReceived[k] === null) {
delete patchedObject[k]
}
else {
patchedObject[k] = objectReceived[k]
}
}
else {
//Note the possibility of notifying the user that these keys were not processed.
delete objectReceived[k]
}
}
if (Object.keys(objectReceived).length === 0) {
//Then you aren't actually changing anything...only @id came through
//Just hand back the object. The resulting of patching nothing is the object unchanged.
res.set(utils.configureWebAnnoHeadersFor(originalObject))
res.location(originalObject["@id"])
res.status(200)
delete originalObject._id
originalObject.new_obj_state = JSON.parse(JSON.stringify(originalObject))
res.json(originalObject)
return
}
const id = ObjectID()
let context = patchedObject["@context"] ? { "@context": patchedObject["@context"] } : {}
let rerumProp = { "__rerum": utils.configureRerumOptions(generatorAgent, originalObject, true, false)["__rerum"] }
delete patchedObject["_rerum"]
delete patchedObject["_id"]
delete patchedObject["@id"]
delete patchedObject["@context"]
let newObject = Object.assign(context, { "@id": process.env.RERUM_ID_PREFIX + id }, patchedObject, rerumProp, { "_id": id })
console.log("PATCH UPDATE")
try {
let result = await db.insertOne(newObject)
if (alterHistoryNext(originalObject, newObject["@id"])) {
//Success, the original object has been updated.
res.set(utils.configureWebAnnoHeadersFor(newObject))
res.location(newObject["@id"])
res.status(200)
delete newObject._id
newObject.new_obj_state = JSON.parse(JSON.stringify(newObject))
res.json(newObject)
return
}
err = Object.assign(err, {
message: `Unable to alter the history next of the originating object. The history tree may be broken. See ${originalObject["@id"]}. ${err.message}`,
status: 500
})
}
catch (error) {
//WriteError or WriteConcernError
next(createExpressError(error))
return
}
}
}
else {
//The http module will not detect this as a 400 on its own
err = Object.assign(err, {
message: `Object in request body must have the property '@id'. ${err.message}`,
status: 400
})
}
next(createExpressError(err))
}
/**
* Update some existing object in MongoDB by adding the keys from the JSON object in the request body.
* Note that if a key on the request object matches a key on the object in MongoDB, that key will be ignored.
* Order the properties to preference @context and @id. Put __rerum and _id last.
* This cannot change or unset existing keys.
* Track History
* Respond RESTfully
* */
const patchSet = async function (req, res, next) {
let err = { message: `` }
res.set("Content-Type", "application/json; charset=utf-8")
let objectReceived = JSON.parse(JSON.stringify(req.body))
let patchedObject = {}
let generatorAgent = getAgentClaim(req, next)
if (objectReceived["@id"]) {
let id = parseDocumentID(objectReceived["@id"])
let originalObject
try {
originalObject = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
} catch (error) {
next(createExpressError(error))
return
}
if (null === originalObject) {
//This object is not in RERUM, they want to import it. Do that automatically.
//updateExternalObject(objectReceived)
err = Object.assign(err, {
message: `This object is not from RERUM and will need imported. This is not automated yet. You can make a new object with create. ${err.message}`,
status: 501
})
}
else if (utils.isDeleted(originalObject)) {
err = Object.assign(err, {
message: `The object you are trying to update is deleted. ${err.message}`,
status: 403
})
}
else {
patchedObject = JSON.parse(JSON.stringify(originalObject))
//A set only adds new keys. If the original object had the key, it is ignored here.
for (let k in objectReceived) {
if (originalObject.hasOwnProperty(k)) {
//Note the possibility of notifying the user that these keys were not processed.
delete objectReceived[k]
}
else {
patchedObject[k] = objectReceived[k]
}
}
if (Object.keys(objectReceived).length === 0) {
//Then you aren't actually changing anything...there are no new properties
//Just hand back the object. The resulting of setting nothing is the object from the request body.
res.set(utils.configureWebAnnoHeadersFor(originalObject))
res.location(originalObject["@id"])
res.status(200)
delete originalObject._id
originalObject.new_obj_state = JSON.parse(JSON.stringify(originalObject))
res.json(originalObject)
return
}
const id = ObjectID()
let context = patchedObject["@context"] ? { "@context": patchedObject["@context"] } : {}
let rerumProp = { "__rerum": utils.configureRerumOptions(generatorAgent, originalObject, true, false)["__rerum"] }
delete patchedObject["_rerum"]
delete patchedObject["_id"]
delete patchedObject["@id"]
delete patchedObject["@context"]
let newObject = Object.assign(context, { "@id": process.env.RERUM_ID_PREFIX + id }, patchedObject, rerumProp, { "_id": id })
try {
let result = await db.insertOne(newObject)
if (alterHistoryNext(originalObject, newObject["@id"])) {
//Success, the original object has been updated.
res.set(utils.configureWebAnnoHeadersFor(newObject))
res.location(newObject["@id"])
res.status(200)
delete newObject._id
newObject.new_obj_state = JSON.parse(JSON.stringify(newObject))
res.json(newObject)
return
}
err = Object.assign(err, {
message: `Unable to alter the history next of the originating object. The history tree may be broken. See ${originalObject["@id"]}. ${err.message}`,
status: 500
})
}
catch (error) {
//WriteError or WriteConcernError
next(createExpressError(error))
return
}
}
}
else {
//The http module will not detect this as a 400 on its own
err = Object.assign(err, {
message: `Object in request body must have the property '@id'. ${err.message}`,
status: 400
})
}
next(createExpressError(err))
}
/**
* Update some existing object in MongoDB by removing the keys noted in the JSON object in the request body.
* Note that if a key on the request object does not match a key on the object in MongoDB, that key will be ignored.
* Order the properties to preference @context and @id. Put __rerum and _id last.
* This cannot change existing keys or set new keys.
* Track History
* Respond RESTfully
* */
const patchUnset = async function (req, res, next) {
let err = { message: `` }
res.set("Content-Type", "application/json; charset=utf-8")
let objectReceived = JSON.parse(JSON.stringify(req.body))
let patchedObject = {}
let generatorAgent = getAgentClaim(req, next)
if (objectReceived["@id"]) {
let id = parseDocumentID(objectReceived["@id"])
let originalObject
try {
originalObject = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
} catch (error) {
next(createExpressError(error))
return
}
if (null === originalObject) {
//This object is not in RERUM, they want to import it. Do that automatically.
//updateExternalObject(objectReceived)
err = Object.assign(err, {
message: `This object is not from RERUM and will need imported. This is not automated yet. You can make a new object with create. ${err.message}`,
status: 501
})
}
else if (utils.isDeleted(originalObject)) {
err = Object.assign(err, {
message: `The object you are trying to update is deleted. ${err.message}`,
status: 403
})
}
else {
patchedObject = JSON.parse(JSON.stringify(originalObject))
delete objectReceived._id //can't unset this
delete objectReceived.__rerum //can't unset this
delete objectReceived["@id"] //can't unset this
/**
* unset does not alter an existing key. It removes an existing key.
* The request payload had {key:null} to flag keys to be removed.
* Everything else is ignored.
*/
for (let k in objectReceived) {
if (originalObject.hasOwnProperty(k) && objectReceived[k] === null) {
delete patchedObject[k]
}
else {
//Note the possibility of notifying the user that these keys were not processed.
delete objectReceived[k]
}
}
if (Object.keys(objectReceived).length === 0) {
//Then you aren't actually changing anything...no properties in the request body were removed from the original object.
//Just hand back the object. The resulting of unsetting nothing is the object.
res.set(utils.configureWebAnnoHeadersFor(originalObject))
res.location(originalObject["@id"])
res.status(200)
delete originalObject._id
originalObject.new_obj_state = JSON.parse(JSON.stringify(originalObject))
res.json(originalObject)
return
}
const id = ObjectID()
let context = patchedObject["@context"] ? { "@context": patchedObject["@context"] } : {}
let rerumProp = { "__rerum": utils.configureRerumOptions(generatorAgent, originalObject, true, false)["__rerum"] }
delete patchedObject["_rerum"]
delete patchedObject["_id"]
delete patchedObject["@id"]
delete patchedObject["@context"]
let newObject = Object.assign(context, { "@id": process.env.RERUM_ID_PREFIX + id }, patchedObject, rerumProp, { "_id": id })
console.log("PATCH UNSET")
try {
let result = await db.insertOne(newObject)
if (alterHistoryNext(originalObject, newObject["@id"])) {
//Success, the original object has been updated.
res.set(utils.configureWebAnnoHeadersFor(newObject))
res.location(newObject["@id"])
res.status(200)
delete newObject._id
newObject.new_obj_state = JSON.parse(JSON.stringify(newObject))
res.json(newObject)
return
}
err = Object.assign(err, {
message: `Unable to alter the history next of the originating object. The history tree may be broken. See ${originalObject["@id"]}. ${err.message}`,
status: 500
})
}
catch (error) {
//WriteError or WriteConcernError
next(createExpressError(error))
return
}
}
}
else {
//The http module will not detect this as a 400 on its own
err = Object.assign(err, {
message: `Object in request body must have the property '@id'. ${err.message}`,
status: 400
})
}
next(createExpressError(err))
}
/**
* Replace some existing object in MongoDB with the JSON object in the request body.
* Order the properties to preference @context and @id. Put __rerum and _id last.
* DO NOT Track History
* Respond RESTfully
* */
const overwrite = async function (req, res, next) {
let err = { message: `` }
res.set("Content-Type", "application/json; charset=utf-8")
let objectReceived = JSON.parse(JSON.stringify(req.body))
let agentRequestingOverwrite = getAgentClaim(req, next)
if (objectReceived["@id"]) {
console.log("OVERWRITE")
let id = parseDocumentID(objectReceived["@id"])
let originalObject
try {
originalObject = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
} catch (error) {
next(createExpressError(error))
return
}
if (null === originalObject) {
err = Object.assign(err, {
message: `No object with this id could be found in RERUM. Cannot overwrite. ${err.message}`,
status: 404
})
}
else if (utils.isDeleted(originalObject)) {
err = Object.assign(err, {
message: `The object you are trying to overwrite is deleted. ${err.message}`,
status: 403
})
}
else if (utils.isReleased(originalObject)) {
err = Object.assign(err, {
message: `The object you are trying to overwrite is released. Fork with /update to make changes. ${err.message}`,
status: 403
})
}
else if (!utils.isGenerator(originalObject, agentRequestingOverwrite)) {
err = Object.assign(err, {
message: `You are not the generating agent for this object. You cannot overwrite it. Fork with /update to make changes. ${err.message}`,
status: 401
})
}
else {
let context = objectReceived["@context"] ? { "@context": objectReceived["@context"] } : {}
let rerumProp = { "__rerum": originalObject["__rerum"] }
rerumProp["__rerum"].isOverwritten = new Date(Date.now()).toISOString().replace("Z", "")
const id = originalObject["_id"]
//Get rid of them so we can enforce the order
delete objectReceived["@id"]
delete objectReceived["@context"]
delete objectReceived["_id"]
delete objectReceived["__rerum"]
let newObject = Object.assign(context, { "@id": originalObject["@id"] }, objectReceived, rerumProp, { "_id": id })
let result
try {
result = await db.replaceOne({ "_id": id }, newObject)
} catch (error) {
next(createExpressError(error))
}
if (result.modifiedCount == 0) {
//result didn't error out, the action was not performed. Sometimes, this is a neutral thing. Sometimes it is indicative of an error.
}
res.set(utils.configureWebAnnoHeadersFor(newObject))
res.location(newObject["@id"])
delete newObject._id
newObject.new_obj_state = JSON.parse(JSON.stringify(newObject))
res.json(newObject)
return
}
}
else {
//This is a custom one, the http module will not detect this as a 400 on its own
err = Object.assign(err, {
message: `Object in request body must have the property '@id'. ${err.message}`,
status: 400
})
}
next(createExpressError(err))
}
/**
* Public facing servlet to release an existing RERUM object. This will not
* perform history tree updates, but rather releases tree updates.
* (AKA a new node in the history tree is NOT CREATED here.)
*
* The id is on the URL already like, ?_id=.
*
* The user may request the release resource take on a new Slug id. They can do this
* with the HTTP Request header 'Slug' or via a url parameter like ?slug=
*/
const release = async function (req, res, next) {
let agentRequestingRelease = getAgentClaim(req, next)
let id = req.params["_id"]
let slug = ""
let err = {"message":""}
let treeHealed = false
if(req.get("Slug")){
let slug_json = await generateSlugId(req.get("Slug"), next)
if(slug_json.code){
next(createExpressError(slug_json))
return
}
else{
slug = slug_json.slug_id
}
}
if (id){
let originalObject
try {
originalObject = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
}
catch (error) {
next(createExpressError(error))
return
}
let safe_original = JSON.parse(JSON.stringify(originalObject))
let previousReleasedID = safe_original.__rerum.releases.previous
let nextReleases = safe_original.__rerum.releases.next
if (utils.isDeleted(safe_original)) {
err = Object.assign(err, {
message: `The object you are trying to release is deleted. ${err.message}`,
status: 403
})
}
if (utils.isReleased(safe_original)) {
err = Object.assign(err, {
message: `The object you are trying to release is already released. ${err.message}`,
status: 403
})
}
if (!utils.isGenerator(safe_original, agentRequestingRelease)) {
err = Object.assign(err, {
message: `You are not the generating agent for this object. You cannot release it. ${err.message}`,
status: 401
})
}
if (err.status) {
next(createExpressError(err))
return
}
console.log("RELEASE")
if (null !== originalObject){
safe_original["__rerum"].isReleased = new Date(Date.now()).toISOString().replace("Z", "")
safe_original["__rerum"].releases.replaces = previousReleasedID
safe_original["__rerum"].slug = slug
if (previousReleasedID !== "") {
// A releases tree exists and an ancestral object is being released.
treeHealed = await healReleasesTree(safe_original)
}
else {
// There was no releases previous value.
if (nextReleases.length > 0) {
// The release tree has been established and a descendant object is now being released.
treeHealed = await healReleasesTree(safe_original)
}
else {
// The release tree has not been established
treeHealed = await establishReleasesTree(safe_original)
}
}
if (treeHealed) {
// If the tree was established/healed
// perform the update to isReleased of the object being released. Its
// releases.next[] and releases.previous are already correct.
let releasedObject = safe_original
let result
try {
result = await db.replaceOne({ "_id": id }, releasedObject)
}
catch (error) {
next(createExpressError(error))
return
}
if (result.modifiedCount == 0) {
//result didn't error out, the action was not performed. Sometimes, this is a neutral thing. Sometimes it is indicative of an error.
}
res.set(utils.configureWebAnnoHeadersFor(releasedObject))
res.location(releasedObject["@id"])
console.log(releasedObject._id+" has been released")
delete releasedObject._id
releasedObject.new_obj_state = JSON.parse(JSON.stringify(releasedObject))
res.json(releasedObject)
return
}
}
}
else{
//This was a bad request
err = {
message: "You must provide the id of an object to release. Use /release/id-here or release?_id=id-here.",
status: 400
}
next(createExpressError(err))
return
}
}
/**
* Query the MongoDB for objects containing the key:value pairs provided in the JSON Object in the request body.
* This will support wildcards and mongo params like {"key":{$exists:true}}
* The return is always an array, even if 0 or 1 objects in the return.
* */
const query = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
let props = req.body
const limit = parseInt(req.query.limit ?? 100)
const skip = parseInt(req.query.skip ?? 0)
if (Object.keys(props).length === 0) {
//Hey now, don't ask for everything...this can happen by accident. Don't allow it.
let err = {
message: "Detected empty JSON object. You must provide at least one property in the /query request body JSON.",
status: 400
}
next(createExpressError(err))
return
}
try {
let matches = await db.find(props).limit(limit).skip(skip).toArray()
matches =
matches.map(o => {
delete o._id
return o
})
res.set(utils.configureLDHeadersFor(matches))
res.json(matches)
} catch (error) {
next(createExpressError(error))
}
}
/**
* Query the MongoDB for objects with the _id provided in the request body or request URL
* Note this specifically checks for _id, the @id pattern is irrelevant.
* Note /v1/id/{blank} does not route here. It routes to the generic 404
* */
const id = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
let id = req.params["_id"]
try {
let match = await db.findOne({"$or": [{"_id": id}, {"__rerum.slug": id}]})
if (match) {
res.set(utils.configureWebAnnoHeadersFor(match))
//Support built in browser caching
res.set("Cache-Control", "max-age=86400, must-revalidate")
//Support requests with 'If-Modified_Since' headers
res.set(utils.configureLastModifiedHeader(match))
res.location(match["@id"])
delete match._id
res.json(match)
return
}
let err = new Error(`No RERUM object with id '${id}'`)
err.status = 404
throw err
} catch (error) {
next(createExpressError(error))
}
}
const bulkCreate = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
const documents = req.body
// TODO: validate documents gatekeeper function?
if (!Array.isArray(documents)) {
let err = new Error("The request body must be an array of objects.")
//err.status = 406
err.status = 400
next(err)
return
}
if (documents.length === 0) {
let err = new Error("No action on an empty array.")
//err.status = 406
err.status = 400
next(err)
return
}
if (documents.filter(d=>d["@id"] ?? d.id).length > 0) {
let err = new Error("`/bulkCreate` will only accept objects without @id or id properties.")
//err.status = 422
err.status = 400
next(err)
return
}
// TODO: bulkWrite SLUGS? Maybe assign an id to each document and then use that to create the slug?
// let slug = req.get("Slug")
// if(slug){
// const slugError = await exports.generateSlugId(slug)
// if(slugError){
// next(createExpressError(slugError))
// return
// }
// else{
// slug = slug_json.slug_id
// }
// }
let bulkOps = []
documents.forEach(d => {
const id = ObjectID()
let generatorAgent = getAgentClaim(req, next)
d = utils.configureRerumOptions(generatorAgent, d)
// TODO: check profiles/parameters for 'id' vs '@id' and use that
d._id = id
d['@id'] = `${process.env.RERUM_ID_PREFIX}${id}`
bulkOps.push({ insertOne : { "document" : d }})
})
try {
let dbResponse = await db.bulkWrite(bulkOps)
res.set("Content-Type", "application/json; charset=utf-8")
res.set("Link",dbResponse.result.insertedIds.map(r => `${process.env.RERUM_ID_PREFIX}${r._id}`)) // https://www.rfc-editor.org/rfc/rfc5988
res.status(201)
const estimatedResults = bulkOps.map(f=>{
let doc = f.insertOne.document
delete doc._id
return doc
})
res.json(estimatedResults) // https://www.rfc-editor.org/rfc/rfc7231#section-6.3.2
}
catch (error) {
//MongoServerError from the client has the following properties: index, code, keyPattern, keyValue
next(createExpressError(error))
}
}
/**
* Allow for HEAD requests by @id via the RERUM getByID pattern /v1/id/
* No object is returned, but the Content-Length header is set.
* Note /v1/id/{blank} does not route here. It routes to the generic 404
* */
const idHeadRequest = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
let id = req.params["_id"]
try {
let match = await db.findOne({"$or":[{"_id": id}, {"__rerum.slug": id}]})
if (match) {
const size = Buffer.byteLength(JSON.stringify(match))
res.set("Content-Length", size)
res.sendStatus(200)
return
}
let err = new Error(`No RERUM object with id '${id}'`)
err.status = 404
throw err
} catch (error) {
next(createExpressError(error))
}
}
/**
* Allow for HEAD requests via the RERUM getByProperties pattern /v1/api/query
* No objects are returned, but the Content-Length header is set.
*/
const queryHeadRequest = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
let props = req.body
try {
let matches = await db.find(props).toArray()
if (matches.length) {