Skip to content

Instantly share code, notes, and snippets.

@jasoncrawford
Last active December 18, 2015 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasoncrawford/5771050 to your computer and use it in GitHub Desktop.
Save jasoncrawford/5771050 to your computer and use it in GitHub Desktop.
Start of a simple promise-based HTTP client, based on Q-IO and inspired by SuperAgent
var http = require('q-io/http');
var BufferStream = require('q-io/buffer-stream');
// Response
function Response(promise) {
this.promise = promise;
this.status = this.promise.get('status');
this.buffer = this.promise.then(function (response) {
return response.body.read();
});
this.body = this.buffer.then(function (buffer) {
return JSON.parse(buffer.toString());
});
}
// Client
function Client(baseUrl) {
this.baseUrl = baseUrl;
}
// Assumes content type JSON for now
Client.prototype.post = function (path, bodyObject) {
var url = this.baseUrl + path;
var request = http.normalizeRequest(url);
request.method = 'POST';
request.headers['content-type'] = 'application/json';
var json = JSON.stringify(bodyObject);
request.body = BufferStream(new Buffer(json));
var promise = http.request(request);
return new Response(promise);
}
// exports
module.exports = Client;
// Example of how this could be used in a test using Mocha, Chai, mocha-as-promised and chai-as-promised
var client = new Client('http://localhost:5000');
describe('User creation', function () {
describe('when an email is submitted', function () {
var response;
before(function () {
response = client.post('/users', {email: 'jason@jasoncrawford.org'});
});
it('should return 201 Created', function () {
return expect(response.status).eventually.equal(201);
});
it('should return a user object with an ID', function () {
return expect(response.body.get('_id')).eventually.ok;
});
it('should return a user object with the same email given', function () {
return expect(response.body.get('email')).eventually.equal('jason@jasoncrawford.org');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment