我有一个我正在尝试验证的唯一数据:
{
"name": "Some random name",
"blocks": [
{"cj5458hyl0001zss42td3waww": {
"quantity": 9,
"rate": 356.77,
"dId": "ewdwe4434"
}},
{"cj5458hyl0001zss42td3wawu": {
"quantity": 4,
"rate": 356.77,
"dId": "3434ewdwe4434"
}}]
}
这是我现在的作文(无效且不正确):
const subSchema = {
"type": ["string"],
"pattern": "/^c[^\s-]{8,}$/",
"properties": {
"quantity": {
"type": "integer"
},
"rate": {
"type": "integer"
},
"dId": {
"type": "string"
}
},
"required": ["quantity", "rate", "dId"]
};
const schema = {
"type": ["object"],
"properties": {
"name": {
"type": "string"
},
"blocks": {
"type": "array",
"items": subSchema,
"uniqueItems": true,
"minItems": 1
}
},
"required": ["name", "blocks"]
};
以及我如何验证它(针对上下文):
const { BadRequestError } = require("restify");
const ajv = require("ajv");
var schemaValidator = ajv();
const validateRoomTypePostRequest = (req, res, next) => {
if (req.body && req.body.data){
const blockReq = Object.assign({}, req.body.data);
const testSchemaValidator = schemaValidator.compile(schema);
const valid = testSchemaValidator(blockReq);
if (!valid) {
const messages = testSchemaValidator.errors.map(e => {
return e.message;
});
return next(new BadRequestError(JSON.stringify(messages)));
}
return next();
}
else {
return next(new BadRequestError("Invalid or non-existent request body"));
}
};
以下是我到目前为止所引用的内容:
2) https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md
3) https://spacetelescope.github.io/understanding-json-schema/reference/object.html
附加信息:
1) 使用节点 8.1.3
2) AJV 5.2版
我知道我需要使用一组项目来描述对象。然而,该对象包含一个唯一的 cuid 作为键和作为对象的值。我想了解如何使用验证嵌套属性和 cuid 的模式来描述这些数据。我欢迎有关如何最好地处理这些数据的反馈。感谢您的时间。