Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recommended way to extend the request class? #280

Open
jayceekay opened this issue Jan 18, 2021 · 0 comments
Open

Recommended way to extend the request class? #280

jayceekay opened this issue Jan 18, 2021 · 0 comments

Comments

@jayceekay
Copy link

jayceekay commented Jan 18, 2021

I was hoping to make a helper method for assisting with auth, eg. chai.request(app).get('/users').withAuth() which would ensure:

  • a user is dynamically inserted in the db
  • the user gets authenticated and a bearer token is generated and persisted (via passport)
  • the token gets set in the req's auth header
  • the user gets set in the req context (eg. req.user)

i've been putzing around trying to wrap chaiHttp just so i can wrap lib/request, then set that wrapper as chai.request rather than lib/request, but to no avail (i can't keep the 'this' context). is there a template i could borrow, or could someone point me in the right direction?

this is one approach i've tried:

import util from 'util';
import chaiHttp from 'chai-http';
import chaiRequest from 'chai-http/lib/request';

export default function MyWrapper(chai, _) {
  chaiHttp.call(this, chai, _);

  function MyRequestWrapper() {
    const args = Array.prototype.slice.call(arguments);
    return chaiRequest.apply(this, args);
  }

  util.inherits(MyRequestWrapper, chaiRequest);

  MyRequestWrapper.prototype.withAuth = () => { // optionally pass in account to authenticate
    // not working
    // this.set('authorization', `bearer ${someUser.token}`);
  };

  chai.request = MyRequestWrapper;
};

i've also tried this in the constructor:

let obj = chaiRequest.apply(this, args);
obj.withAuth = () => {}; // etc...
return obj;

but no go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant