Skip to content

Instantly share code, notes, and snippets.

@brandon-beacher
Created October 9, 2009 15:13
Show Gist options
  • Select an option

  • Save brandon-beacher/206094 to your computer and use it in GitHub Desktop.

Select an option

Save brandon-beacher/206094 to your computer and use it in GitHub Desktop.
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