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?