ES6 Class, pass function as parameter to register expressjs routes

Viewed 8680

This class is used to extend all the controllers inside my expressjs application:

import response from '../utils/responseParser.js';

const APISLUG = '/api/v1/';

export default class BaseController {

  constructor(name, app, model){
    this.model = model;
    this.app = app;
    this.name = name;
    console.log(model);
    this.register();
  }

  register() {
    this.app.get(APISLUG + this.name, this.all);
  }
  /*
  Retrive all records
  */
  all(req, res, next) {
    this.model.all(req.body, (err, data) => {
      if(err) return res.json(response.replyError(data));
      return res.json(response.reply(data));
    });
  }
}

As you can see I have made a " register" method to automatically set-up all the basic routes.

I get a error unable to read property " model " of undefined " on this line:

this.app.get(APISLUG + this.name, this.all);

I believe this is due to the fact that the scope get lost when I pass the function as parameter. How can I solve this?

2 Answers
Related