Last active
December 15, 2015 04:08
-
-
Save pulkitsinghal/5199005 to your computer and use it in GitHub Desktop.
This file contains 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) { | |
// Use ?debug=true to enable debug logging | |
if (req.query.debug) log({"Started update handler with argument doc: ": doc}) | |
if (req.query.debug) log({"Started update handler with argument req: ": req}) | |
var response = {'ok':true} | |
if (req.query.debug) log('Receive Vend webhook: ' + req.body) | |
var payload; | |
if (req.form && req.form.payload) { | |
try { payload = JSON.parse(req.form.payload) } | |
catch (er) { return fail('Bad JSON body for payload: ' + JSON.stringify(req.form.payload)) } | |
} | |
if (!doc) { | |
if (req.query.debug) log('New product received. Payload ID: ' + payload.id) | |
doc = payload | |
doc._id = payload.id | |
} else { | |
// we never enter this block because the request coming from Vend never sets the "id" | |
if (req.query.debug) log('Product update received. Payload ID: ' + payload.id) | |
if (req.query.debug) log('Old doc: ' + JSON.stringify(doc)) | |
// a) get the revision # and id # from the doc that already exists | |
payload._rev = doc._rev | |
payload._id = doc._id | |
// b) might as well update the entire document with the new payload | |
// rather than trying to do a tricky merge | |
doc = payload | |
} | |
if (req.query.debug) log('Finishing update handler with doc: ' + JSON.stringify(doc)) | |
return respond(201) | |
// | |
// Utilities | |
// | |
function fail(reason) { | |
log('Vend ERROR: ' + JSON.stringify(reason)) | |
doc = null | |
return respond(400, {'error':reason}) | |
} | |
function respond(code, body) { | |
body = body || response | |
body = JSON.stringify(body) + "\n" | |
return [doc, {'code':code, 'body':body}] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment