我正在尝试使用REST api
和node js
为我的数据库设置express
。
现在我一直是分而治之的粉丝,因此我对创建REST api in node j
时会得到的冗余代码和大量服务器文件感到有点不安。
在用户表上进行示例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");
});
});
现在这只适用于一张桌子。
所以我认为必须有更好的方法来组织所有这些?
所以我的问题是你能否将每条路由划分为一个单独的文件,是否有办法简化数据的路由/收集,以便删除冗余?
答案 0 :(得分:2)
我就是这样做的:
//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);
所以基本上我创建了一个中间件来处理指定路径的请求。你甚至可以通过迭代你拥有的所有控制器文件并要求它们来简化这个过程,但我喜欢它就像那样:)
更新:
您可以将依赖项直接传递给控制器:
//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);