Reputation: 13
What I'm attempting is to create a Controller Class that will initialize all my routes for me with ExpressJS here's a basic example of what I have
class Test extends Controller {
constructor(App) {
const Routes = [
{
url: '/hello',
execute: this.world
}
];
super({ Routes });
};
world(req, res) {
return res.json({success: true, msg: "Hello World."});
}
}
Controller Class
class Controller {
constructor({ Routes }) {
// I want to be able to access the items from the Routes Object here so I can loop over them and initialize them
}
}
I need a way to pass this routes Object into the Controller class, It needs to have the URL so that if a route has params such as /hello/:id
then that would be defined there and it needs to know which function to execute in the Test class.
The issue is Your not allowed to access the this
parameter before the super has been called and you can't access it within the super either. Is there any way that I can get this object through?
Is this possible or am I missing something really obvious
Upvotes: 0
Views: 350
Reputation: 614
Define your routes as a static const routes
and pass the child class in the constructor as
super(Test)
From the parent, you can access in the constructor
constructor(Test) {
this.routes = Test.routes
}
This should solve the problem.
Upvotes: 0