Skip to content

Commit

Permalink
fix: store('scope').update() ignores scope
Browse files Browse the repository at this point in the history
Ensures that when calling `store('scope').update(...)`, that only items in scope are updated.  Items out of scope are ignored.

This code assumes the following:
* `storedObjects` is an array with the exact same size as `objectsOrIds`
* `objectsOrIds` is either a string, an object, a list of strings, or a list of objects
* if `objectsOrIds` is not an array then it is a single string representing an id or a single object and, as a result, `storedObjects` will either be null or a single object
* when attempting to find a single objectOrId, a single object is returned (rather than an array with one object)
* every item returned by find() will have an id associated with it.
  • Loading branch information
capellini committed Aug 27, 2016
1 parent 6dfbaf2 commit b2fa9dd
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion lib/scoped/update.js
@@ -1,11 +1,57 @@
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) {
return api.update(objectsOrIds, change)
// 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 = updateObjects(objectsOrIds, storedObjects)

return api.update(updatedObjects, change)

.then(function (apiUpdates) {
if (!Array.isArray(apiUpdates)) {
return apiUpdates
}

return restoreOriginalFindErrors(updatedObjects, apiUpdates)
})
})
}

function updateObjects (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)
})
}

function updateObject (objectOrId, storedObject) {
if (typeof objectOrId !== 'object') {
return storedObject
}

return merge(storedObject, objectOrId)
}

function restoreOriginalFindErrors (updatedObjects, apiUpdates) {
return updatedObjects.map(function (updatedObject, index) {
if (updatedObject instanceof Error) {
return updatedObject
}

return apiUpdates[index]
})
}

0 comments on commit b2fa9dd

Please sign in to comment.