我将 REST 调用中的数据条目分为 4 个部分。数据可以通过以下方式发送到 REST 调用:-
- 标题
- 查询参数
- 路径参数
- 请求正文
因此,为了验证上述 4 个部分中是否存在任何键,我以这种格式创建了一个模式。因此,如果我必须验证查询参数中的任何内容,我将添加键“查询”,然后在其中添加字段,这需要验证
const schema = {
id: 'Users_login_post',
type: 'object',
additionalProperties: false,
properties: {
headers: {
type: 'object',
additionalProperties: false,
properties: {
Authorization: {
type: 'string',
minLength: 10,
description: 'Bearer token of the user.',
errorMessages: {
type: 'should be a string',
minLength: 'should be atleast of 23 length',
required: 'should have Authorization'
}
}
},
required: ['Authorization']
},
path: {
type: 'object',
additionalProperties: false,
properties: {
orgId: {
type: 'string',
minLength: 23,
maxLength: 36,
description: 'OrgId Id of the Organization.',
errorMessages: {
type: 'should be a string',
minLength: 'should be atleast of 23 length', // ---> B
maxLength: 'should not be more than 36 length',
required: 'should have OrgId'
}
}
},
required: ['orgId']
}
}
};
现在,在我的快速代码中,我创建了一个请求对象,以便我可以测试这种格式的 JSON 的有效性。
router.get("/org/:orgId/abc", function(req, res){
var request = { //---> A
path: {
orgId : req.params.orgId
},
headers: {
Authorization : req.headers.Authorization
}
}
const Ajv = require('ajv');
const ajv = new Ajv({
allErrors: true,
});
let result = ajv.validate(schema, request);
console.log(ajv.errorsText());
});
我使用AjV针对我的模式验证上述请求对象(在 A 处)。
我得到的输出如下所示:
data/headers should have required property 'Authorization', data/params/orgId should NOT be shorter than 23 characters
现在我有一个问题清单:
- 为什么即使我的变量名称是request(在 A 处) ,消息也会在data/headers和data/params/orgId中显示数据字
- 另外为什么不使用我的错误消息,就像我提到的 orgId 的情况一样:应该至少23长度(在 B 处)作为消息,即使这样消息来也不应该短于 23 个字符。
- 如何显示request/headers而不是data/headers。
另外,我用来验证路径参数、查询参数、标题参数、正文参数的方式是正确的方式,如果不是,那么还有什么更好的方式来做同样的事情?
请阐明一些观点。
提前致谢。