import{Request,Response}from"express";import{UserService}from"../services/UserService";import{IUser}from"../models/User";exportclassUserController{privateuserService:UserService;constructor(){this.userService=newUserService();// Bind the methods to the current contextthis.create=this.create.bind(this);this.findAll=this.findAll.bind(this);this.findById=this.findById.bind(this);this.update=this.update.bind(this);this.delete=this.delete.bind(this);}asynccreate(req:Request,res:Response){constdata:IUser=req.body;constuser=awaitthis.userService.create(data);res.json(user);}asyncfindAll(req:Request,res:Response){constusers=awaitthis.userService.findAll();res.json(users);}asyncfindById(req:Request,res:Response){constid=req.params.id;constuser=awaitthis.userService.findById(id);res.json(user);}asyncupdate(req:Request,res:Response){constid=req.params.id;constdata:IUser=req.body;constuser=awaitthis.userService.update(id,data);res.json(user);}asyncdelete(req:Request,res:Response){constid=req.params.id;constuser=awaitthis.userService.delete(id);res.json(user);}}
importexpressfrom"express";importcorsfrom"cors";importdotenvfrom"dotenv";importconnectDBfrom"./config/database";importuserRoutesfrom"./routes/userRoutes";dotenv.config();connectDB();constapp=express();app.use(express.json());app.use(cors());app.use("/users",userRoutes);constPORT=process.env.PORT||5000;app.listen(PORT,()=>{console.log(`Server running on port ${PORT}`);});
### Create a user
POST http://localhost:5000/users
Content-Type: application/json
{
"name": "John Doe",
"email": "a@c.c",
}
### Get all users
GET http://localhost:5000/users
### Get a user by id
GET http://localhost:5000/users/1
### Update a user
PUT http://localhost:5000/users/1
Content-Type: application/json
{
"name": "Jane Doe",
"email": "b@c.c",
}
### Delete a user
DELETE http://localhost:5000/users/1
Run the following command to start the server
npm run dev
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)