I am developing a straightforward REST API using TypeScript that interacts with your classes to query a database in the following sequence:
Controller > Service > Repository
.
While working on this, I experimented with the following code snippets:
Controller:
export class GetNurseController {
constructor(private getNurseService: GetNurseService) {}
async handle(req: Request, res: Response): Promise<Response> {
try {
const { id } = req.authrocket.currentUser;
const user = await this.getNurseService.execute(id);
return res.json({ user });
} catch (err: any) {
return res.status(500).json({ err });
// Although the json returns an empty error object, an undefined error related to "getNurseService" is displayed in my console.
}
}
}
Router:
const nurseRepository = new NurseRepository();
const getNurseService = new GetNurseService(nurseRepository);
const getNurseController = new GetNurseController(getNurseService);
const nurseRoutes = Router();
nurseRoutes.get('/', requireLogin, getNurseController.handle);
Another approach with Controller:
export class GetNurseController {
public NurseRepository: INurseRepository;
public getNurseService: GetNurseService;
constructor() {
this.nurseRepository = new NurseRepository();
this.getNurseService = new GetNurseService(this.nurseRepository);
}
async handle(req: Request, res: Response): Promise<Response> {
try {
const { id } = req.authrocket.currentUser;
const user = await this.getNurseService.execute(id);
return res.json({ user });
} catch (err: any) {
return res.status(500).json({ err });
}
}
}
Despite trying different variations of the code above, I consistently face either empty errors or encounter connection issues when accessing the route.
However, modifying the code as shown below yields successful results:
Controller:
export class GetNurseController {
async handle(req: Request, res: Response): Promise<Response> {
try {
const nurseRepository = new nurseRepository();
const getNurseService = new GetNurseService(nurseRepository);
const { id } = req.authrocket.currentUser;
const user = await getNurseService.execute(id);
return res.json({ user });
} catch (err: any) {
return res.status(500).json({ err });
}
}
}
Router:
const getNurseController = new GetNurseController();
const nurseRoutes = Router();
nurseRoutes.get('/', requireLogin, getNurseController.handle);
If anyone can shed some light on what may be going wrong or if my objectives are achievable, I would greatly appreciate it.