Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

".use" method to add logic on each request of SuperAgent

This issue in SuperAgent repository mentions the .use method to add logic on each request. For example, adding an Authorization header for JWT when a token is available:

superagent.use( bearer );

function bearer ( request ) {
    var token = sessionStorage.get( 'token' );

    if ( token ) request.set( 'Authorization', 'Bearer ' + token );
}

Although the last comment informs that this feature is working again, I can't make it to work.

The following test code:

var request = require( 'superagent' );

request.use( bearer );

function bearer ( request )
{
    // "config" is a global var where token and other stuff resides
    if ( config.token ) request.set( 'Authorization', 'Bearer ' + config.token );
}

Returns this error:

request.use( bearer );
        ^
TypeError: undefined is not a function
like image 325
Paulo Coghi Avatar asked May 29 '15 19:05

Paulo Coghi


1 Answers

The issue you linked to isn't linked to any commits, so all we can do is speculate on whether or not that feature was implemented and then removed, or never implemented in the first place.

If you read through the src, you will see that use is only ever defined on the prototype of the Request constructor, meaning it can only ever be used after you've began constructing a request, as shown in the readme.

In other words, the issue seems to be talking about a feature that either has been removed, or never existed. You should instead use the syntax mentioned in the readme.

var request = require('superagent');

request
.get('/some-url')
.use(bearer) // affects **only** this request
.end(function(err, res){
    // Do something
});

function bearer ( request ){
    // "config" is a global var where token and other stuff resides
    if ( config.token ) {
        request.set( 'Authorization', 'Bearer ' + config.token );
    }
}

You could of course create your own wrapper so that you don't have to do it for every request.

var superagent = require('superagent');

function request(method, url) {
    // callback
    if ('function' == typeof url) {
        return new superagent.Request('GET', method).end(url).use(bearer);
    }

    // url first
    if (1 == arguments.length) {
        return new superagent.Request('GET', method).use(bearer);
    }

    return new superagent.Request(method, url).use(bearer);
} 
// re-implement the .get and .post helpers if you feel they're important..

function bearer ( request ){
    // "config" is a global var where token and other stuff resides
    if ( config.token ) {
        request.set( 'Authorization', 'Bearer ' + config.token );
    }
}

request('GET', '/some-url')
.end(function(err, res){
    // Do something
});
like image 106
Kevin B Avatar answered Sep 28 '22 07:09

Kevin B