Last active
December 18, 2015 10:49
-
-
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
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
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; |
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
// 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