如何创建一个单一的API来获取所有用户和获取单个用户?

huangapple go评论76阅读模式
英文:

How to create single API for getallUsers and getUser?

问题

To create a single API that can handle both getting all users and a single user, you can use a route like this:

router.get('/:id?', async (req, res) => {
    if (req.params.id) {
        // Get a single user by ID
        const user = await User.findById(req.params.id).select('-password');
        if (!user) {
            res.status(404).json({ message: 'User not found' });
        } else {
            res.status(200).json(user);
        }
    } else {
        // Get all users
        const userList = await User.find().select('-password');
        res.status(200).json(userList);
    }
});

This route handles requests with or without an id parameter. If an id is provided, it retrieves a single user by ID. If not, it retrieves all users.

英文:

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?

答案1

得分: 1

你可以告诉客户,如果他们需要所有用户,他们应该将"id"参数设为"all"。

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: "未找到给定id的用户" });
    }
    res.status(200).send(user);
  }
});
英文:

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);
  }
});

答案2

得分: 0

使用路由器

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);
英文:

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);

huangapple
  • 本文由 发表于 2023年1月4日 19:52:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75005047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定