如何正确处理我的 REST 路由 API

How to properly handle my routing for a REST API

如果这是新手问题,我们深表歉意。我应该如何构建我的 REST API(我使用 Node & Express)。

const mongoose = require('mongoose');

const recipeSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'UserData',
        required: true
    },
    description: String,
    ingredients: [String],
    steps: [String],
    bookmarkNumber: Number,
    likeNumber: Number,
    rating: Number
})

module.exports = mongoose.model('Recipe', recipeSchema); 

据我所知,我可以使用以下内容来实现更大规模的功能,例如创建食谱和删除食谱以及 e.t.c

router.get('/', (req, res, next) => {
  // Get Recipes
});

router.post('/',checkAuth, (req, res, next) => {
  // Create Recipe
});

router.get('/:recipeID', (req, res, next) => {
// Get Specific Recipe
});

然而,我目前卡在如何处理内部细节或特定资源上。例如:假设我想在食谱中添加一个步骤。这个具体实例是我可以放置动词还是?我目前的想法是:

router.post('/:recipeID/steps',checkAuth, (req, res, next) => {
  // Add Steps to recipeID if it exists
});

所以基本上添加属性的 url 并以这种方式处理它们,因为动词显然是 REST API 罪过。

router.post('/:recipeID/:steps',checkAuth, (req, res, next) => {
   if (req.params.steps === 'first') {//based on your requirements

     } else if (condition) {

     }
});

但是,对于不同的操作,还有一些其他 API 规则。

  • GET /users: 获取用户列表。
  • GET /users/:userid : 获取特定用户的信息。
  • POST /users: 创建用户。
  • PUT /users 更新特定用户信息。

它可能会帮助您了解设计 API 端点的最佳方法。