Last active
April 26, 2018 10:13
-
-
Save 7ictor/83a9580cddd408f983a7 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' | |
})]; | |
} |
Thanks @brhrmaster, I forgot to update after publish and test 😄
How do i use this partial-update.js in my pouch code
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you please fix this: instead of return newDoc object the database needs to receive the modified DOC object.
return [ doc, JSON.stringify({ status: 'updated' }) ];