-
Notifications
You must be signed in to change notification settings - Fork 29
/
update.js
300 lines (258 loc) · 8.22 KB
/
update.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
const async = require('async')
const debug = require('debug')('api:model')
const Hook = require('./../hook')
const logger = require('@dadi/logger')
/**
* Block with metadata pertaining to an API collection.
*
* @typedef {Object} Metadata
* @property {Number} page - current page
* @property {Number} offset - offset from start of collection
* @property {Number} totalCount - total number of documents
* @property {Number} totalPages - total number of pages
* @property {Number} nextPage - number of next available page
* @property {Number} prevPage - number of previous available page
*/
/**
* @typedef {Object} ResultSet
* @property {Metadata} metadata - object with collection metadata
* @property {Array} results - list of documents
*/
/**
* Finds documents in the database, running any configured hooks
* and formatting the result set for final output.
*
* @param {Object} query - query to match documents against
* @param {Object} options
* @param {Object} req - request object to pass to hooks
* @return {Promise<ResultSet>}
*/
/**
* @param {Object} client - client to check permissions for
* @param {Boolean|Number} compose - the composition settings for the result
* @param {Object} query - query to match documents against
* @param {Object} update - properties to update documents with
* @param {Object} internals - internal properties to inject in documents
* @param {Boolean} rawOutput - whether to bypass output formatting
* @param {Boolean} removeInternalProperties - whether to remove internal properties
* @param {Object} req - request object to pass to hooks
* @param {Boolean} validate - whether to run validation
* @return {Promise<Array.ResultSet>} set of updated documents
*/
function update ({
client,
compose = true,
query = {},
update,
internals = {},
rawOutput = false,
removeInternalProperties = true,
req,
validate = true
}) {
debug(
'Model update: %s %o %o %o',
req ? req.url : '',
query,
update,
internals
)
if (!this.connection.db) {
return Promise.reject(
new Error('DB_DISCONNECTED')
)
}
// Add `lastModifiedAt` internal field.
internals._lastModifiedAt = internals._lastModifiedAt || Date.now()
// Is this a RESTful query by ID?
let isRestIDQuery = req && req.params && req.params.id
// Get a reference to the documents that will be updated.
let updatedDocuments = []
return this.validateAccess({
client,
query,
type: 'update'
}).then(({query: aclQuery, schema}) => {
query = aclQuery
// If merging the request query with ACL data resulted in
// an impossible query, we can simply return an empty result
// set without even going to the database. We'll reject the
// Promise now and catch this case at the end of the chain.
if (query instanceof Error) {
return Promise.reject(query)
}
// Removing internal API properties from the update object.
if (removeInternalProperties) {
update = this.removeInternalProperties(update)
}
if (!validate) return
// Validating the query.
let queryValidation = this.validateQuery(query)
if (!queryValidation.success) {
let error = this._createValidationError('Bad Query')
error.json = queryValidation
return Promise.reject(error)
}
return this.validator.validateDocument({
document: update,
isUpdate: true,
schema
}).catch(errors => {
let error = this._createValidationError('Validation Failed', errors)
return Promise.reject(error)
})
}).then(() => {
// Format the query.
query = this.formatQuery(query)
return this.find({
query
})
}).then(({results}) => {
// Create a copy of the documents that matched the find
// query, as these will be updated and we need to send back
// to the client a full result set of modified documents.
updatedDocuments = results
// Add any internal fields to the update.
Object.assign(update, internals)
// Run `beforeSave` hooks on update fields.
return Object.keys(update).reduce((result, field) => {
if (field === '_id') {
return result
}
return result.then(transformedUpdate => {
return this.runFieldHooks({
data: {
internals,
updatedDocuments
},
field,
input: {
[field]: update[field]
},
name: 'beforeSave'
}).then(subDocument => {
return Object.assign({}, transformedUpdate, subDocument)
})
})
}, Promise.resolve({})).then(transformedUpdate => {
update = transformedUpdate
// Run any `beforeUpdate` hooks.
if (this.settings.hooks && this.settings.hooks.beforeUpdate) {
return new Promise((resolve, reject) => {
async.reduce(this.settings.hooks.beforeUpdate, update, (current, hookConfig, callback) => {
let hook = new Hook(hookConfig, 'beforeUpdate')
Promise.resolve(hook.apply(current, updatedDocuments, this.schema, this.name, req))
.then(newUpdate => {
callback((newUpdate === null) ? {} : null, newUpdate)
}).catch(err => {
callback(hook.formatError(err))
})
}, (error, newUpdate) => {
if (error) {
reject(error)
}
resolve(newUpdate)
})
})
}
return update
}).then(update => {
return this.connection.db.update({
collection: this.name,
options: {
multi: true
},
query,
schema: this.schema,
update: {
$set: update,
$inc: { _version: 1 }
}
})
}).then(({matchedCount}) => {
if (isRestIDQuery && (matchedCount === 0)) {
let error = new Error('Not Found')
error.statusCode = 404
return Promise.reject(error)
}
// Create a revision for each of the updated documents.
if (this.history) {
return this.history.createEach(
updatedDocuments,
'update',
this
)
}
}).then(() => {
let updatedDocumentsQuery = {
_id: {
'$in': updatedDocuments.map(doc => doc._id.toString())
}
}
return this.find({
query: updatedDocumentsQuery,
options: {
compose: true
}
})
}).then(data => {
if (data.results.length === 0) {
return data
}
// Run any `afterUpdate` hooks.
if (this.settings.hooks && (typeof this.settings.hooks.afterUpdate === 'object')) {
this.settings.hooks.afterUpdate.forEach((hookConfig, index) => {
let hook = new Hook(this.settings.hooks.afterUpdate[index], 'afterUpdate')
return hook.apply(data.results, this.schema, this.name)
})
}
// Asynchronous search index.
this.searchHandler.index(data.results)
// Format result set for output.
if (!rawOutput) {
return this.formatForOutput(data.results, {
client,
composeOverride: compose
}).then(results => {
return Object.assign({}, data, {
results
})
})
}
return data
})
}).catch(error => {
// Dealing with the case of an impossible query. We can simply return
// an empty result set here.
if (error.message === 'EMPTY_RESULT_SET') {
return this._buildEmptyResponse()
}
logger.error({ module: 'model' }, error)
return Promise.reject(error)
})
}
module.exports = function () {
// Compatibility with legacy model API.
// Signature: query, update, internals, done, req, bypassOutputFormatting
if (arguments.length > 1) {
let callback
let legacyArguments = {
query: arguments[0],
rawOutput: arguments[5],
req: arguments[4],
update: arguments[1]
}
if (typeof arguments[2] === 'function') {
callback = arguments[2]
legacyArguments.internals = {}
} else {
callback = arguments[3]
legacyArguments.internals = arguments[2]
}
update.call(this, legacyArguments)
.then(response => callback && callback(null, response))
.catch(error => callback && callback(error))
return
}
return update.apply(this, arguments)
}