Skip to content

Instantly share code, notes, and snippets.

@yssk22
Created December 5, 2010 07:23
Show Gist options
  • Save yssk22/728913 to your computer and use it in GitHub Desktop.
Save yssk22/728913 to your computer and use it in GitHub Desktop.
CouchDB proxy middleware
/*******************************************
* Connect middleware to proxy request to
* the specified path on CouchDB.
*
* Usage:
*
* app.use(express.bodyDecoder());
* app.use(function(req, res, next){
* res.bindings = res.bindings || {};
* });
*
* app.get('/news', couchdb.proxiedTo("/_design/posts/_view/by_tag", {
* startkey: ["news", "\u0000"],
* endkey: ["news"],
* descending: true,
* limit: 10
* }), function(req, res){
* res.writeHead(200);
* res.end(JSON.stringify(res.bindings))
* });
*
*******************************************/
var url = require('url'),
querystring = require('querystring');
var $ = require('jquery');
var db = require('config').couchdb;
exports.proxiedTo = function(path, params){
return function(req, res, next){
var urlObj = url.parse(req.url, true);
var query = $.extend({}, urlObj.query, params);
var request = {
method: req.method,
path: path
};
if( req.method == "POST" || req.method == "PUT" ){
request.data = req.body;
}
db.request(request,
function(err, doc){
res.bindings['couchdb.proxiedTo.err'] = err;
res.bindings['couchdb.proxiedTo.doc'] = doc;
next();
});;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment