Created
October 9, 2009 15:13
-
-
Save brandon-beacher/206094 to your computer and use it in GitHub Desktop.
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 createCouchRequest = function(httpClient, method, path, params) { | |
| var couchRequest = {}, | |
| httpClient = httpClient, | |
| method = method, | |
| path = path, | |
| body = ''; | |
| if (method === 'get') { | |
| path += toQueryString(params); | |
| } else { | |
| body = JSON.stringify(params); | |
| } | |
| var buffer = function(callback) { | |
| request = httpClient[method](path); | |
| if (body) { request.sendBody(body) }; | |
| var responseBody = ''; | |
| request.finish(function(response) { | |
| response.addListener('body', function(chunk) { responseBody += chunk; }); | |
| response.addListener('complete', function() { | |
| callback.call(null, response, JSON.parse(responseBody)); | |
| }); | |
| }); | |
| }; | |
| var stream = function(streamRequest, streamResponse) { | |
| // any reason to forward streamRequest.headers as the second param here? | |
| request = httpClient[method](path /*, streamRequest.headers */); | |
| streamRequest.addListener('body', function(chunk) { | |
| request.sendBody(chunk); | |
| }); | |
| request.finish(function (response) { | |
| // any reason to forward the response.headers as the second param here? | |
| streamResponse.sendHeader(response.statusCode /*, response.headers */); | |
| response.addListener('body', function (chunk) { | |
| streamResponse.sendBody(chunk); | |
| }); | |
| response.addListener('complete', function () { | |
| streamResponse.finish(); | |
| }); | |
| }); | |
| }; | |
| var toQueryString = function(params) { | |
| var queryString = ''; | |
| for (var key in params) { | |
| queryString += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); | |
| } | |
| return queryString.length > 0 ? '?' + queryString : ''; | |
| }; | |
| couchRequest.buffer = buffer; | |
| couchRequest.stream = stream; | |
| return couchRequest; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment