Permalink
Browse files

.ok()

Fixes #1069

Closes #1096 #1074
  • Loading branch information...
1 parent 9c8df95 commit 34533bbc29833889090847c45a82b0ea81b2f06d @pornel pornel committed Dec 13, 2016
Showing with 58 additions and 0 deletions.
  1. +8 −0 docs/index.md
  2. +9 −0 lib/request-base.js
  3. +41 −0 test/basic.js
View
@@ -523,6 +523,14 @@ An "error" event is also emitted, with you can listen for:
// all other error types we handle generically
}
+Alternatively, you can use the `.ok(callback)` method to decide whether a response is an error or not. The callback to the `ok` function gets a response and returns `true` if the response should be interpreted as success.
+
+ request.get('/404')
+ .ok(res => res.status < 500)
+ .then(response => {
+ // reads 404 page as a successful response
+ })
+
## Promise and Generator support
SuperAgent's request is a "thenable" object that's compatible with JavaScript promises and `async`/`await` syntax. Do not call `.end()` if you're using promises.
View
@@ -142,12 +142,21 @@ RequestBase.prototype.use = function use(fn) {
return this;
}
+RequestBase.prototype.ok = function(cb) {
+ if ('function' !== typeof cb) throw Error("Callback required");
+ this._okCallback = cb;
+ return this;
+};
RequestBase.prototype._isResponseOK = function(res) {
if (!res) {
return false;
}
+ if (this._okCallback) {
+ return this._okCallback(res);
+ }
+
return res.status >= 200 && res.status < 300;
};
View
@@ -102,7 +102,32 @@ describe('request', function(){
});
})
+
describe('res.error', function(){
+ it('ok', function(done){
+ var calledErrorEvent = false;
+ var calledOKHandler = false;
+ request
+ .get(uri + '/error')
+ .ok(function(res){
+ assert.strictEqual(500, res.status);
+ calledOKHandler = true;
+ return true;
+ })
+ .on('error', function(err){
+ calledErrorEvent = true;
+ })
+ .end(function(err, res){
+ try{
+ assert.ifError(err);
+ assert.strictEqual(res.status, 500);
+ assert(!calledErrorEvent);
+ assert(calledOKHandler);
+ done();
+ } catch(e) { done(e); }
+ });
+ });
+
it('should should be an Error object', function(done){
var calledErrorEvent = false;
request
@@ -141,6 +166,22 @@ describe('request', function(){
assert.equal(err.message, 'Internal Server Error');
});
})
+
+ it('with .ok() returning false', function(){
+ if ('undefined' === typeof Promise) {
+ return;
+ }
+
+ return request
+ .get(uri + '/echo')
+ .ok(function() {return false;})
+ .then(function(){
+ assert.fail();
+ }, function(err){
+ assert.equal(200, err.response.status);
+ assert.equal(err.message, 'OK');
+ });
+ })
})
describe('res.header', function(){

0 comments on commit 34533bb

Please sign in to comment.