Greetings and thank you for taking the time to peruse through this. I am venturing into the realm of express.js and typescript and have stumbled upon an intriguing issue. I am currently trying to unravel the mystery behind why 'this' is undefined in the functions of CompanyRouter.
The initialization of the router appears as follows:
this.express.use('/api/v1/company', new CompanyRouter(new CompanyService()).router);
Could it be a matter of context, or does express.js view router functions as static functions?
import {Router, Request, Response, NextFunction} from 'express';
import {Company} from '../models/Company';
import {ICompanyService} from '../interfaces/ICompanyService';
export class CompanyRouter {
router: Router
service: ICompanyService
constructor(service : ICompanyService) {
this.router = Router();
this.service = service;
this.init();
}
init() {
this.router.get('/', this.getAllCompanies);
this.router.post('/', this.postCompany);
}
public async getAllCompanies(req: Request, res: Response, next: NextFunction) {
const companies = this.service.findAll()
res.send(companies);
}
public async postCompany(req: Request, res: Response, next: NextFunction) {
const company = this.service.add(req.body);
res.send(company);
}
}