-
Notifications
You must be signed in to change notification settings - Fork 16
/
update.js
59 lines (46 loc) · 1.53 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
module.exports = update
var find = require('./find')
var merge = require('lodash/merge')
function update (type, api, objectsOrIds, change) {
return find(type, api, objectsOrIds)
.then(function (storedObjects) {
// objectsOrIds may contain updated information for the respective storedObject
// (e.g. _deleted = true), so incorporate all information in the objectOrId into
// the storedObject
var updatedObjects = updateObjectsAndFilterErrors(objectsOrIds, storedObjects)
return api.update(updatedObjects, change)
.then(function (apiUpdates) {
if (!Array.isArray(apiUpdates)) {
return apiUpdates
}
return restoreOriginalFindErrors(storedObjects, apiUpdates)
})
})
}
function updateObjectsAndFilterErrors (objectsOrIds, storedObjects) {
if (!Array.isArray(objectsOrIds)) {
return updateObject(objectsOrIds, storedObjects)
}
return storedObjects.map(function (storedObject, index) {
if (storedObject instanceof Error) {
return storedObject
}
return updateObject(objectsOrIds[index], storedObject)
}).filter(function (storedObject) {
return !(storedObject instanceof Error)
})
}
function updateObject (objectOrId, storedObject) {
if (typeof objectOrId !== 'object') {
return storedObject
}
return merge(storedObject, objectOrId)
}
function restoreOriginalFindErrors (foundObjects, apiUpdates) {
return foundObjects.map(function (foundObject) {
if (foundObject instanceof Error) {
return foundObject
}
return apiUpdates.shift()
})
}