Created
December 5, 2010 07:23
-
-
Save yssk22/728913 to your computer and use it in GitHub Desktop.
CouchDB proxy middleware
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
/******************************************* | |
* 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