-
-
Save evert0n/873f5286cfc8d8755176c9c633e3ab7a to your computer and use it in GitHub Desktop.
CouchDB update handler for partial updates of a document.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function (doc, req) { | |
var findTheChanges = function (prevK, obj) { | |
var arr = []; | |
for (var key in obj) { | |
var prevKey = prevK || ''; | |
if (obj.hasOwnProperty(key)) { | |
var value = obj[key]; | |
// If its an Object dig deeper. | |
if (value !== null && | |
typeof value === 'object' && | |
value.constructor !== Array) { | |
prevKey += key; | |
prevKey += ','; | |
var deepArr = findTheChanges(prevKey, value); | |
arr = arr.concat(deepArr); | |
} | |
// Found the value to affect. | |
else { | |
arr.push({ | |
path: prevKey + key, | |
value: value | |
}); | |
} | |
} | |
} | |
return arr; | |
}; | |
if (!doc) { | |
return [null, JSON.stringify({ | |
doc: req.id, | |
status: 'nodoc' | |
})]; | |
} | |
var _obj = JSON.parse(req.body); | |
var arrayOfChanges = findTheChanges(null, _obj); | |
for (var i = 0, len1 = arrayOfChanges.length; i < len1; i++) { | |
var path = (arrayOfChanges[i].path).split(','); | |
var value = arrayOfChanges[i].value; | |
var newDoc = doc; | |
for (var j = 0, len2 = path.length; j < len2; j++) { | |
// If it's not the final value, and niether is an Object, | |
// it should be an empty Object to build the new chain. | |
if (j + 1 < len2 && | |
(typeof newDoc[path[j]] !== 'object' || | |
newDoc[path[j]].constructor === Array || | |
newDoc[path[j]] === null)) { | |
newDoc[path[j]] = {}; | |
} | |
if (j + 1 === len2) newDoc[path[j]] = value; | |
else newDoc = newDoc[path[j]]; | |
} | |
} | |
return [doc, JSON.stringify({ | |
doc: req.id, | |
status: 'updated' | |
})]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment