I'm having trouble passing a class method as an Express route parameter. I've attempted to bind the method and also tried using arrow functions, but neither approach has worked for me.
My project involves TypeORM, and I keep encountering the error message "Connection 'default' was not found." However, if I include the complete function directly as the parameter, everything runs smoothly.
router.get("/", async (_req: Request, res: Response) => {
try {
const projects: Project[] = await new ProjectService().findAll();
res.status(200).send(projects);
} catch (e) {
res.status(404).send(e.message);
}
});
The code snippet below doesn't yield the desired results.
ProjectRoutes.ts
const router: Router = Router();
const projectController = new ProjectController();
router.get("/", projectController.getAllProjects);
export default router;
ProjectController.ts
export class ProjectController {
projectService: ProjectService = new ProjectService();
getAllProjects = async (_req: Request, res: Response) => {
try {
const projects: Project[] = await this.projectService.findAll();
return res.status(200).send(projects);
} catch (e) {
return res.status(404).send(e.message);
}
};
}
ProjectService.ts
export class ProjectService {
projectRepository: ProjectRepository;
constructor() {
this.projectRepository = getCustomRepository(ProjectRepository);
}
async findAll(): Promise<Project[]> {
return await this.projectRepository.findAll();
}
}
ProjectRepository
@EntityRepository(Project)
export class ProjectRepository extends Repository<Project> {
async findAll(): Promise<Project[]> {
return await this.find();
}
}
Routes index.ts
const router: Router = Router();
router.use("/projects", ProjectRoutes);
export default router;
Server.ts
app.use("/", router);