gpt4 book ai didi

Node.js、Express、Mongoose - 输入验证 - 在路由或模型中?

转载 作者:搜寻专家 更新时间:2023-10-31 22:42:14 24 4
gpt4 key购买 nike

我有一个接受 JSON 帖子的 rest api 资源。示例:

{
"location": {
"coordinates": [
-122.41941550000001,
37.7749295
]
}

然后 Express 从请求中收集坐标:

module.exports.create = function(req, res, next) {

var coordinates = req.body.location.coordinates;
....

然后将这些提交给 Mongoose 模型。我正在针对缺少 location.coordinates 的地方编写测试,例如

{
"foo": {
"bar": [
-122.41941550000001,
37.7749295
]
}

然后这在模型的验证部分失败了:

locationSchema.path('location.coordinates').validate(function(coordinates){
^
TypeError: Cannot call method 'validate' of undefined

所以我的问题是如何验证输入是否正确?这应该在到达模型之前在 route 完成,还是应该在模型中完成?也将不胜感激。

作为引用,Mongoose 模型看起来像这样:

var locationSchema = new Schema({
userid: { type: Number, required: true },
location: {
type: [{
type: "String",
required: true,
enum: ['Point', 'LineString', 'Polygon'],
default: 'Point'
}], required: true,
coordinates: { type: [Number], required:true }
},
create_date: { type: Date, default: Date.now }
});


locationSchema.path('location.coordinates').validate(function(coordinates){
...
}, 'Invalid latitude or longitude.');

最佳答案

我的典型方法是在路由和模型之间引入一个服务层,这就是验证发生的地方。不要在“网络服务”的意义上思考“服务”;它只是围绕给定域提供一个抽象级别。这有以下好处:

  • 它为您提供了处理持久数据和/或外部数据的通用抽象。也就是说,无论您是与来自 Mongoose 还是外部网络服务的数据进行交互,您的所有路由逻辑都可以简单地与一致的界面进行交互。
  • 它提供围绕持久性细节的可靠封装,允许您在不影响所有路由的情况下更换实现。
  • 它允许您对非路由使用者(例如集成测试套件)重复使用代码。
  • 它提供了一个很好的模拟层(例如用于单元测试)。
  • 它提供了一个非常清晰的“验证和业务逻辑发生在这里”层,即使您的数据分布在多个不同的数据库和/或后端系统中也是如此。

这是一个可能看起来像的简化示例:

location-service.js

var locationService = module.exports = {};

locationService.saveCoordinates = function saveCoordinates(coords, cb) {
if (!isValidCoordinates(coords)) {
// your failed validation response can be whatever you want, but I
// like to reserve actual `Error` responses for true runtime errors.
// the result here should be something your client-side logic can
// easily consume and display to the user.
return cb(null, {
success: false,
reason: 'validation',
validationError: { /* something useful to the end user here */ }
});
}

yourLocationModel.save(coords, function(err) {
if (err) return cb(err);

cb(null, { success: true });
});
};

some-route-file.js

app.post('/coordinates', function(req, res, next) {
var coordinates = req.body.location.coordinates;

locationService.saveCoordinates(coordinates, function(err, result) {
if (err) return next(err);

if (!result.success) {
// check result.reason, handle validation logic, etc.
} else {
// woohoo, send a 201 or whatever you need to do
}
});
});

此时我已经将这种结构应用于 3 或 4 个不同的网络应用程序和 API,并且越来越喜欢它。

关于Node.js、Express、Mongoose - 输入验证 - 在路由或模型中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267424/

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