Last active
December 16, 2015 08:49
-
-
Save pulkitsinghal/5408964 to your computer and use it in GitHub Desktop.
Use NodeJS and Cradle to route updates Vend to CouchDB
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
# local env. | |
$ export COUCH_HOST=https://xxx.couchdb.com | |
$ export COUCH_PORT=xxx | |
$ export COUCH_USERNAME=xxx | |
$ export COUCH_PASSWORD=xxx | |
$ export COUCH_DATABASE=xxx | |
# cloud env. | |
$ heroku config:add COUCH_HOST=https://xxx.couchdb.com | |
$ heroku config:add COUCH_PORT=xxx | |
$ heroku config:add COUCH_USERNAME=xxx | |
$ heroku config:add COUCH_PASSWORD=xxx | |
$ heroku config:add COUCH_DATABASE=xxx |
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
var http = require('http'), | |
form2json = require('form2json'), | |
cradle = require('cradle'); | |
cradle.setup({ | |
host: process.env.COUCH_HOST, | |
port: process.env.COUCH_PORT, | |
cache: true, | |
raw: false | |
}); | |
var adminConnection = new(cradle.Connection) ( | |
process.env.COUCH_HOST, | |
process.env.COUCH_PORT, | |
{ | |
auth: { | |
username: process.env.COUCH_USERNAME, | |
password: process.env.COUCH_PASSWORD | |
} | |
} | |
); | |
http.createServer(function (req, res) { | |
var fullBody = ''; | |
req.on('data', function(chunk) { | |
// append the current chunk of data to the fullBody variable | |
fullBody += chunk.toString(); | |
}); | |
req.on('end', function() { | |
var jsonBody = form2json.decode(fullBody); | |
var payload = JSON.parse(jsonBody.payload); | |
payload.type = jsonBody.type; | |
var vendDB = adminConnection.database(process.env.COUCH_DATABASE); | |
vendDB.merge( | |
payload.id, | |
payload, | |
function (err, res) { | |
if (err) { | |
console.log('No previous entry, adding...'); | |
//console.error(err); | |
vendDB.save( | |
payload.id, | |
payload, | |
function (err, res) { | |
if (err) { | |
console.log('Failed to save...'); | |
console.error(err); | |
} else { | |
console.log('Added!'); | |
console.log(res); | |
} | |
} | |
); | |
} else { | |
console.log('Found previous entry, updating...'); | |
console.log(res); | |
} | |
} | |
); | |
res.writeHead(200, "OK", {'Content-Type': 'text/html'}); | |
res.end(); | |
}); | |
req.on('error', function(e) { | |
console.log('problem with request: ' + e.message); | |
}); | |
}).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment