Im building a simple rest api in typescript+expressjs. I wanted to build it with classes and i'm stuck on the part with routing classes. My idea was to build a base class (baseRouter) that could be extended by specific routers (IndexRouter). But trying to do this, i end up registering routes from baseRouter and not the IndexRouter. What am i doing wrong?
export class baseRouter {
protected static _inst: baseRouter;
protected _router: express.Router;
protected _routeBase: string = "/base";
protected constructor() { }
public static route(router: express.Router) {
if (typeof this._inst === 'undefined') this._inst = new this();
this._inst._router = router;
this._inst._registerRoutes();
}
protected _registerRoutes() {
this._router.get(this._routeBase, this._doGet);
console.log('Calling base route');
}
protected _doGet(req: express.Request, res: express.Response) {
res.status(200);
res.send('isBase');
}
}
export class indexRouter extends baseRouter {
protected _routeBase = "/index";
protected _registerRoutes() {
this._router.get(this._routeBase, this._doGet);
console.log('Calling index route');
}
protected _doGet(req: express.Request, res: express.Response) {
res.status(200);
res.send('isIndex');
}
protected _doPost(req: express.Request, res: express.Response) {
res.status(200);
res.send('isIndexPost');
}
}
Entry method to both classes is .route(router). Ideally my solution to my understanding was going to be like:
BaseRouter.route() -> calls baseRouter._registerRoutes() -> ...
IndexRouter.route() -> calls indexRouter._registerRoutes() -> ...
Is this achievable without redeclaring .route() function every time?
BaseRouter.route()it callsBaseRouter._registerRoutesand when callingIndexRouter.route()it callsIndexRouter._registerRoutes(though there's no need to have this method twice)