Skip to content

Recommended way to extend the request class? #280

@jayceekay

Description

@jayceekay

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions