1

I'm trying to use ES6 classes (using TypeScript) to write express.js controllers. What I was hoping to achieve was to have a 'base' controller, looking something like this:

class Controller {
    private Model: any

    constructor(Model: any) {
        this.Model = Model;
    }

    showModel(req: any, res: any) {
        res.status(200).json(await this.Model.findById(req.params.id).lean());
    }
}

export default Controller;

And that I would then be able to inherit that showModel method on another controller, such as:

import Controller from "../controller";

class VideoController extends Controller {

    constructor(Model: any) {
        super(Model);
    }

    // Other methods

}

and lastly to call the VideoController, feed it a DB-model, and fetch something from my DB, like:


const VideoService = new VideoController(VideoModel);

router.route('/video/:id')
    .get(VideoService.showModel)

However, I keep getting the error: TypeError: Cannot read property 'Model' of undefined, and cannot really figure out why all of a sudden the showModel() method would not have access to the class constructor. What am I overlooking?

1 Answers1

2

By writing VideoService.showModel you are passing a reference to a function that is "detached" from the class (it's just a regular function, not a method as you expect, and this is undefined when it executes).

Write this instead:

.get(() => VideoService.showModel())

Other alternative:

.get(VideoService.showModel.bind(VideoService))
Guerric P
  • 30,447
  • 6
  • 48
  • 86