2

抱歉,如果这是一个新手问题。我应该如何构建我的 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); 

虽然我知道我可以将以下内容用于更大规模的功能,例如创建食谱和删除食谱等

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 的罪过。

4

1 回答 1

1
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 端点的最佳方法。

于 2019-03-20T09:11:19.550 回答