我正在尝试在 sailsjs v0.11.0 上构建REST API,我正在寻找一种验证所有POST请求的方法。验证适用于简单模型。
简单模型示例: 的 category.js
module.exports = {
attributes: {
name: {
type: 'string',
required: true, // this works, the POST data is validated, if this field is missing, sails responds with an error json
unique: true
}
}
}
关联的一对多模型示例,其中验证不起作用:
Chapter.js
module.exports = {
attributes: {
name: 'string',
categoryId: 'integer',
pages: {
type: 'string',
required: true // Sails saves the record to DB even if this field is missing.
},
owner: {
model: 'Upload'
}
}
};
Upload.js
module.exports = {
attributes: {
draftId: 'integer',
chapters: {
collection: 'Chapter',
via: 'owner'
}
}
};
修改
我使用了以下更新的Chapter.js 模型,但是如果相关模型验证失败,那么sails服务器将以500状态和错误json响应,如下所示,不是错误,应该发送400状态。
更新了Chapter.js:
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
categoryId: {
type: 'integer',
required: true
},
pages: {
type: 'string',
required: true
},
owner: {
model: 'Upload'
}
}
};
状态为500的错误:
{
"error": "E_UNKNOWN",
"status": 500,
"summary": "Encountered an unexpected error",
"raw": [
{
"type": "insert",
"collection": "chapter",
"values": {
"name": "chapeterOne",
"pages": "2,3,4,5",
"owner": 12
},
"err": {
"error": "E_VALIDATION",
"status": 400,
"summary": "1 attribute is invalid",
"model": "Chapter",
"invalidAttributes": {
"categoryId": [
{
"rule": "integer",
"message": "`undefined` should be a integer (instead of \"null\", which is a object)"
},
{
"rule": "required",
"message": "\"required\" validation rule failed for input: null"
}
]
}
}
}
]
}
有没有办法让错误信息更明智?