Currently, I am working on creating a server using express.js and typescript. In my project, I have an abstract class called Controller
which serves as the base class for all controllers. Additionally, I have a specific class named AuthController
that manages authentication logic. However, when I attempt to send a POST request to the server, I encounter an error message:
TypeError: Cannot read property 'routes' of undefined
at setRoutes (C:\path\to\project\dist\typings\Controller.js:12:34)
at Layer.handle [as handle_request] (C:\path\to\project\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\path\to\project\node_modules\express\lib\router\index.js:317:13)
...
Here is a snippet from my tsconfig file:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"noEmitOnError": true,
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
}
}
Abstract controller class:
export default abstract class Controller {
public router: Router = Router();
public abstract path: string;
protected abstract routes: Array<IRoute> = [];
public setRoutes(): Router {
// Route handling logic here
}
};
Route interface:
export interface IRoute {
// Interface structure
};
Auth controller class:
export default class AuthController extends Controller {
// Class implementation
}
To utilize these controllers in the Server class, I follow this approach:
public loadControllers(controllers: Array<Controller>): void {
// Loading controller logic here
};
Finally, I initialize the controllers in app.ts like so :
const controllers: Array<Controller> = [
new AuthController(),
new OtherController(),
];
server.loadControllers(controllers);