I have to create a single API to get all users and a single user. How can I create an API for this?
Currently, I had APIs like this.
To get All Users:
router.get(`/`, async (req, res) =>{
const userList = await User.find().select('-password')
if(!userList) {
res.status(500).json({success: false})
}
res.send(userList);
})
To get single User:
router.get('/:id' , async (req,res) =>{
const user = await User.findById(req.params.id).select('-password')
if(!user){
res.status(500).json({message: 'The User with give id is not found'})
}
res.status(200).send(user)
})
Now my requirement is that have to create a single API for above both APIs.
How can I solve this?
CodePudding user response:
You can say clients that they should send all as id if they require all the users.
router.get("/:id", async (req, res) => {
if (req.params.id === "all") {
const userList = await User.find().select("-password");
if (!userList) {
res.status(500).json({ success: false });
}
res.send(userList);
} else {
const user = await User.findById(req.params.id).select("-password");
if (!user) {
res.status(500).json({ message: "The User with give id is not found" });
}
res.status(200).send(user);
}
});
CodePudding user response:
Use a router
let router = express.Router();
router.get('/:id', function (req, res, next) {
console.log("Specific User Router Working");
res.end();
});
router.get('/all', function (req, res, next) {
console.log("All User Router Working");
res.end();
});
app.use('/user',router);