[英]express.js API Endpoint Best Practice for CRUD
I'm building a REST API using express.js. 我正在使用express.js构建REST API。
My API needs to provide all endpoints to do CRUD on "users", so I have the following so far: 我的API需要提供所有端点才能对“用户”执行CRUD,所以到目前为止,我有以下内容:
app.get('/users', getAllUsers); // get all users
app.post('/users', createUser); // create a new user
app.put('/users', updateUser); // update a user
app.delete('/users', deleteUser); // delete a user
But whats a good practice endpoint to get a single user? 但是,获得单个用户的最佳做法是什么呢?
So ideally if you GET on /users/1234
I should only return User with ID 1234 but if I just do /users
I should return all users as the ID was not detected. 因此,理想情况下,如果您在/users/1234
上执行GET操作,我应该只返回ID为1234的User,但是如果我只是执行/users
,则应该返回所有用户,因为未检测到ID。
How can I refactor my: 我该如何重构我的:
app.get('/users', getAllUsers);
to handle both cases? 处理这两种情况?
You can create a higher-level router, and then call app.use()
/ router.use()
on it. 您可以创建一个更高级别的路由器,然后在其上调用app.use()
/ router.use()
。 This is the recommended approach in the Express documentation . 这是Express文档中推荐的方法。
var express = require('express');
var app = express();
var usersRouter = express.Router();
usersRouter.get('/', function(req, res) {
res.send('Got all users');
});
usersRouter.get('/:id', function(req, res) {
res.send('Got user ' + req.params.id);
});
app.use('/users', usersRouter);
You cant , the best practice is to isolate your route operations as much as possible. 您不能,最佳实践是尽可能地隔离您的路线操作。 There to get a single id,such route must only get that data. 那里只有一个ID,这种路由只能获取该数据。 Example. 例。
var router = express.Router();
router.route('some/route/id/123').get(function(req,res){
console.log('id');
});
router.route('some/route/all').get(function(req,res){
console.log('all');
});
you can do so by providing id as an optional param and checking that in the controller function 您可以通过提供id作为可选参数并在controller函数中进行检查来实现
for eg. 例如
app.get('/users/:id?', getAllUsers);
But I'd prefer to go with single responsibility principle 但我宁愿遵循单一责任原则
app.get('/users', getAllUsers);
app.get('/users/:id', getUser);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.