I’m a newbie on NodeJS and I’m trying to create a layered project based on NodeJS using Typescript.
This is the folder structure I’m trying to create:
src
controllers
- user.controller.ts
services - user.service.ts
routes - user.routes.ts
index.ts
I’m trying to inject the UserService in my UserController to call a simple function, however it just won’t work.
This is the code I’m trying:
user.controller.ts
import { Request, Response } from "express";
import { UserService } from "../services/user.service";
export class UserController {
private userService: UserService;
constructor(){
this.userService = new UserService('Hello World!');
}
getPing(_req: Request, res: Response) {
const user = new UserService();
const test = userService.ping();
res.send({
some: test,
});
}
}
user.service.ts
export class UserService {
private message: string;
constructor(message: string){
this.message = message;
}
ping(): any {
return {
msg: `Wanna say this: ${this.message}`,
}
}
}
user.route.ts
import express from 'express';
import { UserController } from '../controllers/user.controller';
const router = express.Router();
const userController = new UserController();
router.get('/message', userController.getPing);
export default router;
index.ts
import express from 'express';
import userRoutes from './routes/user.routes';
const app = express();
app.use(express.json());
const PORT = 3000;
app.use('/api/users', userRoutes);
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
})
As simple as that, but when I try to call the route /api/users I get the error:
TypeError: Cannot read properties of undefined (reading 'userService')
This is my package json:
{
"name": "back",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "ts-node-dev src/index.ts",
"tsc": "tsc",
"start": "node build/index.js",
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.21",
"ts-node-dev": "^2.0.0",
"typescript": "^5.4.5"
},
"dependencies": {
"express": "4.19.2"
}
}
What I have already tried is to declare the userService as a const inside the controller method and it works but this I do not think this is a good practice. I want the service ready to be used by all methods in the Controller.
Please could you just direct me on how can I solve this? I’ve been struggling the whole day.
greglui is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.