Giter Club home page Giter Club logo

superagent-defaults's Introduction

superagent-defaults Build Status

Create some defaults for superagent requests

Usage

var defaults = require('superagent-defaults');

// Create a defaults context
var superagent = defaults();

// Setup some defaults
superagent
  .set('my-default-header', 'my-default-value')
  .auth('myUsername', 'myPassword')
  .on('request', function (req) {
    console.log(req.url);
  });

// Use superagent like you always have; the defaults will be applied to
// each request automatically
superagent
  .get('/my-api')
  .end(function(res) {
    console.log(res.text);
  });

You may also pass a function that implements the superagent interface.

var defaults = require('superagent-defaults');
var supertest = require('supertest');

var request = defaults(supertest(app));

request
  .get('/my-test-path')
  .end(function(err, res) {
    console.log(res.text);
  });

Tests

$ npm test

superagent-defaults's People

Contributors

bral avatar camshaft avatar denis-sokolov avatar kamilkopaczyk avatar magicdawn avatar mndvns avatar stolksdorf avatar zertz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

superagent-defaults's Issues

wish: supertest support

Thanks for the useful addition to superagent

It would be useful it could accept the class to modify as an option, so I could use it to extend supertest as well as superagent. The class to modify could still default to superagent.

For some related context, Perl has the problem with it's popular web-browser, LWP::UserAgent, which had lots of extensions by sub-classing. In many cases like this one, you could not combine two useful extension because of the way that LWP::UserAgent was extended. I wrote about that here:

http://perl.qa.narkive.com/pahziYsb/interest-in-converting-lwp-mech-hierarchy-to-roles

If superagent was instead extended through traits or mixins, then those traits could be applied to other classes and still work. Even better, people could apply multiple extensions as they wish. In node.js, Joose.js implements Traits like Perl's Moose roles, and Cocktail.js is another alternative for traits. I haven't looked closely about whether they would be a viable pattern to use for your particular extension.

async .use fn

My use case is renewing an auth token if it is expired before each call.
So I'd like to be able to define a async .use middleware that will check the timestamp and make another request to renew the token if necessary before continuing.

Maybe I'm missing something obvious?

Defaults for responses

More of question for help than an issue really, but was wondering ... is there a way to set any defaults upon response / end? I have a generic "strip prefix" function that needs to be called with all responses, and something like this would be handy:

superagent
.on("end", (res) => {
res.text = clearPrefix(res.text);
});

Ability to pass in custom superagent

It would be nice if I could pass in my own custom superagent instead of using the default require(superagent). Specific use case it that I use superagent-promise.

request.on not working

I want some global error handling with superagent and I can't even get a simple log to work.

ignore the es6. it gets transpiled.

// RequestDefaults.js
import defaults from 'superagent-defaults';
const request = defaults();

request.on('error', (err) => { console.log(err) });

export default request

Then the subsequent request as usual:

// APIUtils.js

import request from './RequestDefaults';
request
        .post(base + '/v1/login')
        .send({ alias: alias, password: password })
        .end(function(err, res){
            // Some stuff
        });

I would expect a 401 response to trigger the default log, but it does not.

EDIT:

Upon further investigation. It actually doesn't work at all. The request goes out, but NO DEFAULTS ARE APPLIED. Im trying to export the default context after some configuration to be used across my application. Could that be the problem?

Per endpoint defaults?

I was wondering whether it would be possible to set the defaults based on the endpoints that are called? Something like:

// Setup some defaults per endoint
superagent
  .set('my-default-header', 'my-default-value')
  .auth('myUsername', 'myPassword');

// Pseudo
if(url == '/admin') {
superagent
  // overwrite default username and password
  .auth('admin', 'someAdminPassword');
}

Support for superagent-proxy

Hi,

I'm stuck behind a firewall, corporate/hotel/entertainment venue etc, and need to get superagent to obey proxy settings. Is it possible this could be extended and add support for superagent-proxy so we can define a proxy once as a default?

Many thanks,

Ash

Can't return in promise resolve

I'm trying to create a wrapper for superagent with defaults with an authorization header from a callout like:

module.exports = () =>
  new Promise((resolve, reject) => {
    superagent
      .post('https://blah.com/session')
      .send({
        user: 'blah',
        pass: 'blah'
      })
      .then(result => {
        let api = Defaults()
        let base = Prefix('blah')

        api
          .use(base)
          .set({
            'Authorization': result.body.auth_token,
            'Accept': 'application/json'
          })

        resolve(api)
      })
      .catch(err => {
        console.log('api login failed')
        reject(err)
      })
  })

But when I try to use it like below, it successfully gets to the resolve(api) line but never gets to the conn.get line.

api()
  .then(conn => conn.get('/test'))

If I do the same just resolving with superagent without defaults it works. Not sure what's going on ๐Ÿ˜ข

.on() method not working.

From the source index.js

Emitter(Context.prototype)

Just wonder, why not pass on() method to supeagent's request? instead of create your own emitter.

UPDATE

Although use() can make it works, that needs extra typings, and different from original way.

Besides the implementation at https://github.com/camshaft/superagent-defaults/blob/master/lib/context.js#L71 may cause bug.

Original on("reponse", fn) is called when actually made a HTTP request, while this one is called immediately (before make a HTTP request), that is different behavior than original implementation.

Default expectations

Hello,

I'd like to use this module but I'm having a hard time figuring out if it's possible to set default expectations. Specifically, I want all my calls to .expect('Content-Type', /json/) but, when I add that to the defaults I get:

/Users/lgomez/Projects/api/test/index.js:6
  .expect('Content-Type', /json/);
   ^

TypeError: api.set(...).expect is not a function
    at Object.<anonymous> (/Users/lgomez/Projects/api/test/index.js:6:4)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at /Users/lgomez/Projects/api/node_modules/mocha/lib/mocha.js:216:27
    at Array.forEach (native)
    at Mocha.loadFiles (/Users/lgomez/Projects/api/node_modules/mocha/lib/mocha.js:213:14)
    at Mocha.run (/Users/lgomez/Projects/api/node_modules/mocha/lib/mocha.js:453:10)
    at Object.<anonymous> (/Users/lgomez/Projects/api/node_modules/mocha/bin/_mocha:393:18)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Function.Module.runMain (module.js:457:10)
    at startup (node.js:138:18)
    at node.js:974:3

This is how I'm running it:

var defaults = require('superagent-defaults');

var api = defaults(require('supertest')(require('../server'))); // ..server is an expressjs app

api
    .set('Accept', 'application/json')
    .expect('Content-Type', /json/);

describe('/users', function() {

  it('accepts email and password as auth payload', function(done) {

    api.post('/users/auth')
      .send({
        email: '[email protected]',
      })
      .expect(200, done);
  });

});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.