gpt4 book ai didi

javascript - REST路由多个文件 Node js

转载 作者:行者123 更新时间:2023-11-30 17:02:42 25 4
gpt4 key购买 nike

我正在尝试使用 node jsexpress 为我的数据库设置一个 REST api

现在我一直是分而治之的粉丝,因此我对在 Node j 中创建 REST api 时将获得的冗余代码和大量服务器文件感到有点不安.

以对用户表的 CRUD 操作为例:

    // IMPORT ROUTES
// =============================================================================
var router = express.Router();

// on routes that end in /users
// ----------------------------------------------------
router.route('/user')

// create a user (accessed at POST http://localhost:8080/api/users)
.post(function (req, res) {

var username = req.body.username; //bodyParser does the magic
var password = req.body.password;

var user = User.build({username: username, password: password});

user.add(function (success) {
res.json({message: 'User created!'});
},
function (err) {
res.status(err).send(err);
});
})

// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function (req, res) {
var user = User.build();

user.retrieveAll(function (users) {
if (users) {
res.json(users);
} else {
res.status(401).send("User not found");
}
}, function (error) {
res.status("User not found").send('user not found');
});
});


var User = sequelize.define('user', {
id: DataTypes.INTEGER,
username: DataTypes.STRING,
password: DataTypes.STRING,
name: DataTypes.STRING,
organization_id: DataTypes.INTEGER,
type_id: DataTypes.INTEGER,
join_date: DataTypes.STRING,
image_path: DataTypes.STRING,
status_id: DataTypes.INTEGER

}, { freezeTableName: true,
instanceMethods: {
retrieveAll: function (onSuccess, onError) {
User.findAll({}, {raw: true})
.ok(onSuccess).error(onError);
},
retrieveById: function (user_id, onSuccess, onError) {
User.find({where: {id: user_id}}, {raw: true})
.success(onSuccess).error(onError);
},
add: function (onSuccess, onError) {
var username = this.username;
var password = this.password;

var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');

User.build({username: username, password: password})
.save().ok(onSuccess).error(onError);
},
updateById: function (user_id, onSuccess, onError) {
var id = user_id;
var username = this.username;
var password = this.password;

var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');

User.update({username: username, password: password}, {where: {id: id}})
.success(onSuccess).error(onError);
},
removeById: function (user_id, onSuccess, onError) {
User.destroy({where: {id: user_id}}).success(onSuccess).error(onError);
}
}
}
);

// on routes that end in /users/:user_id
// ----------------------------------------------------
router.route('/users/:user_id')

// update a user (accessed at PUT http://localhost:8080/api/users/:user_id)
.put(function (req, res) {
var user = User.build();

user.username = req.body.username;
user.password = req.body.password;

user.updateById(req.params.user_id, function (success) {
console.log(success);
if (success) {
res.json({message: 'User updated!'});
} else {
res.send(401, "User not found");
}
}, function (error) {
res.send("User not found");
});
})

// get a user by id(accessed at GET http://localhost:8080/api/users/:user_id)
.get(function (req, res) {
var user = User.build();

user.retrieveById(req.params.user_id, function (users) {
if (users) {
res.json(users);
} else {
res.status(401).send("User not found");
}
}, function (error) {
res.send("User not found");
});
})

// delete a user by id (accessed at DELETE http://localhost:8080/api/users/:user_id)
.delete(function (req, res) {
var user = User.build();

user.removeById(req.params.user_id, function (users) {
if (users) {
res.json({message: 'User removed!'});
} else {
res.status(401).send("User not found");
}
}, function (error) {
res.send("User not found");
});
});

现在这只适用于一张 table 。

所以我认为一定有更好的方法来组织所有这些?

所以我的问题是,您可以将每条路线分成一个单独的文件吗?有没有一种方法可以简化数据的路线/收集,从而消除冗余?

最佳答案

我是这样做的:

//controllers/someController.js
var express = require('express');
var router = express.Router();

router.post('/something', function(req, res, next) {
...
});
router.get('/something', function(req, res, next) {
...
});

module.exports = router;

//server.js
var app = require('express')();
var someController = require('./controllers/someContoller');
app.use('/some', someController);

所以基本上我创建了一个中间件来处理指定路径的请求。您甚至可以通过遍历您拥有的所有 Controller 文件并要求它们来简化此过程,但我喜欢这样 :)

更新:

您可以将依赖项直接传递给 Controller ​​:

//someController.js
module.exports = function(express) {
var router = express.Router();

router.get('', function() {});

return router;
}

//server.js
var app = require('express')();
var someController = require('./controllers/someContoller')(express);
app.use('/some', someController);

关于javascript - REST路由多个文件 Node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com