Node.js 包装猫鼬验证错误的最佳方法
我们知道猫鼬为我们提供了一种简单的验证方法。但假设您正在使用express+mongoose构建一个微服务;一些客户端(可能是web应用、移动应用等)需要使用它 通常,我更喜欢用简单的错误代码和消息来响应JSON。在大多数情况下,可以创建自己消息的客户端取决于向用户显示的语言 默认情况下,如果我们从mongoose捕获错误,我们可以得到JSON响应,例如: JSON响应 Restful Api控制器 Model Product.js 我所期望的 我正在尝试包装错误消息,以使其对消费者更简单。 可能是这样的:Node.js 包装猫鼬验证错误的最佳方法,node.js,mongodb,mongoose,error-handling,microservices,Node.js,Mongodb,Mongoose,Error Handling,Microservices,我们知道猫鼬为我们提供了一种简单的验证方法。但假设您正在使用express+mongoose构建一个微服务;一些客户端(可能是web应用、移动应用等)需要使用它 通常,我更喜欢用简单的错误代码和消息来响应JSON。在大多数情况下,可以创建自己消息的客户端取决于向用户显示的语言 默认情况下,如果我们从mongoose捕获错误,我们可以得到JSON响应,例如: JSON响应 Restful Api控制器 Model Product.js 我所期望的 我正在尝试包装错误消息,以使其对消费者更简单。 可
{
"errors": [
{
"message": "Path `price` (-1) is less than minimum allowed value (0).",
"code": "100020"
},
{
"message": "Product with given code already exists",
"code": "100021"
}
],
"success": false
}
代码和相应的消息将保存在api文档中。该消息通常有助于消费者理解代码,消费者(如web客户端)可以根据代码创建自己的消息,如法语消息,并显示给最终用户
我如何利用mongoose的valiation来实现这一点?也许我可以循环erros的属性并使用${path}-${kind}
组合一个代码
我知道在大多数情况下,客户端应该在调用API之前进行验证。但在某些情况下,API必须抛出错误
有什么想法吗?我很想知道你最后做了什么。。。(我正在考虑做类似的事情)
exports.createOne = async(function* list(req, res) {
try {
const product = new Product(req.body)
const newProduct = yield product.save()
res.json(newProduct)
} catch (err) {
res.status(400).json(err)
}
})
const mongoose = require('mongoose')
const Schama = mongoose.Schema
const minlength = [5, 'The value of `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'];
const ProductSchema = new Schama({
code: { type: String, required: true, minlength, index: true, unique: true, trim: true, lowercase: true },
name: { type: String, required: true, trim: true },
price: { type: Number, required: true, min: 0, max: 100000 },
categories: [String],
})
ProductSchema.path('code').validate(function uniqueEmail(code, fn) {
const Product = mongoose.model('Product')
// Check only when it is a new Product or when code field is modified
if (this.isNew || this.isModified('code')) {
Product.find({ code }).exec((err, products) => {
fn(!err && products.length === 0)
})
} else fn(true)
}, 'Product with given code already exists')
ProductSchema.statics = {
/**
* List products
*
* @param {Object} options
* @api private
*/
pageList: function pageList(conditions, index, size) {
const criteria = conditions || {}
const page = index || 0
const limit = size || 30
return this.find(criteria)
.populate('user', 'name username')
.sort({ createdAt: -1 })
.limit(limit)
.skip(limit * page)
.exec()
},
}
mongoose.model('Product', ProductSchema)
{
"errors": [
{
"message": "Path `price` (-1) is less than minimum allowed value (0).",
"code": "100020"
},
{
"message": "Product with given code already exists",
"code": "100021"
}
],
"success": false
}