-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbulk.js
More file actions
211 lines (204 loc) · 8.23 KB
/
bulk.js
File metadata and controls
211 lines (204 loc) · 8.23 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
#!/usr/bin/env node
/**
* Bulk operations controller for RERUM operations
* Handles bulk create and bulk update operations
* @author Claude Sonnet 4, cubap, thehabes
*/
import { newID, isValidID, db } from '../database/index.js'
import utils from '../utils.js'
import { _contextid, ObjectID, createExpressError, getAgentClaim, parseDocumentID, idNegotiation } from './utils.js'
/**
* Create many objects at once with the power of MongoDB bulkWrite() operations.
*
* @see https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/
*/
const bulkCreate = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
const documents = req.body
if (!Array.isArray(documents)) {
const err = {
message: "The request body must be an array of objects.",
status: 400
}
next(createExpressError(err))
return
}
if (documents.length === 0) {
const err = {
message: "No action on an empty array.",
status: 400
}
next(createExpressError(err))
return
}
const gatekeep = documents.filter(d=> {
// Each item must be valid JSON, but can't be an array.
if(Array.isArray(d) || typeof d !== "object") return d
try {
JSON.parse(JSON.stringify(d))
} catch (err) {
return d
}
// Items must not have an @id, and in some cases same for id.
const idcheck = _contextid(d["@context"]) ? (d.id ?? d["@id"]) : d["@id"]
if(idcheck) return d
})
if (gatekeep.length > 0) {
const err = {
message: "All objects in the body of a `/bulkCreate` must be JSON and must not contain a declared identifier property.",
status: 400
}
next(createExpressError(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
// }
// }
// unordered bulkWrite() operations have better performance metrics.
const bulkOps = []
const generatorAgent = getAgentClaim(req, next)
for(const d of documents) {
// Do not create empty {}s
if(Object.keys(d).length === 0) continue
const providedID = d?._id
const id = isValidID(providedID) ? providedID : ObjectID()
const configuredDoc = utils.configureRerumOptions(generatorAgent, d)
// id is also protected in this case, so it can't be set.
if(_contextid(configuredDoc["@context"])) delete configuredDoc.id
configuredDoc._id = id
configuredDoc['@id'] = `${process.env.RERUM_ID_PREFIX}${id}`
bulkOps.push({ insertOne : { "document" : configuredDoc }})
}
try {
const dbResponse = await db.bulkWrite(bulkOps, {'ordered':false})
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=>{
const doc = idNegotiation(f.insertOne.document)
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))
}
}
/**
* Update many objects at once with the power of MongoDB bulkWrite() operations.
* Make sure to alter object __rerum.history as appropriate.
* The same object may be updated more than once, which will create history branches (not straight sticks)
*
* @see https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/
*/
const bulkUpdate = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
const documents = req.body
const encountered = []
if (!Array.isArray(documents)) {
const err = {
message: "The request body must be an array of objects.",
status: 400
}
next(createExpressError(err))
return
}
if (documents.length === 0) {
const err = {
message: "No action on an empty array.",
status: 400
}
next(createExpressError(err))
return
}
const gatekeep = documents.filter(d => {
// Each item must be valid JSON, but can't be an array.
if(Array.isArray(d) || typeof d !== "object") return d
try {
JSON.parse(JSON.stringify(d))
} catch (err) {
return d
}
// Items must have an @id, or in some cases an id will do
const idcheck = _contextid(d["@context"]) ? (d.id ?? d["@id"]) : d["@id"]
if(!idcheck) return d
})
// The empty {}s will cause this error
if (gatekeep.length > 0) {
const err = {
message: "All objects in the body of a `/bulkUpdate` must be JSON and must contain a declared identifier property.",
status: 400
}
next(createExpressError(err))
return
}
// unordered bulkWrite() operations have better performance metrics.
const bulkOps = []
const generatorAgent = getAgentClaim(req, next)
for(const objectReceived of documents){
// We know it has an id
const idReceived = objectReceived["@id"] ?? objectReceived.id
// Update the same thing twice? can vs should.
// if(encountered.includes(idReceived)) continue
encountered.push(idReceived)
if(!idReceived.includes(process.env.RERUM_ID_PREFIX)) continue
const 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) continue
if (utils.isDeleted(originalObject)) continue
const newId = ObjectID()
const context = objectReceived["@context"] ? { "@context": objectReceived["@context"] } : {}
const rerumProp = { "__rerum": utils.configureRerumOptions(generatorAgent, originalObject, true, false)["__rerum"] }
delete objectReceived["__rerum"]
delete objectReceived["_id"]
delete objectReceived["@id"]
// id is also protected in this case, so it can't be set.
if(_contextid(objectReceived["@context"])) delete objectReceived.id
delete objectReceived["@context"]
const newObject = Object.assign(context, { "@id": process.env.RERUM_ID_PREFIX + newId }, objectReceived, rerumProp, { "_id": newId })
bulkOps.push({ insertOne : { "document" : newObject }})
if(originalObject.__rerum.history.next.indexOf(newObject["@id"]) === -1){
originalObject.__rerum.history.next.push(newObject["@id"])
const replaceOp = { replaceOne :
{
"filter" : { "_id": originalObject["_id"] },
"replacement" : originalObject,
"upsert" : false
}
}
bulkOps.push(replaceOp)
}
}
try {
const dbResponse = await db.bulkWrite(bulkOps, {'ordered':false})
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(200)
const estimatedResults = bulkOps.filter(f=>f.insertOne).map(f=>{
const doc = idNegotiation(f.insertOne.document)
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))
}
}
export { bulkCreate, bulkUpdate }