Javascript 如何将cuid作为键,值作为具有特定特性的对象来描述和验证对象数组
我有一个我正在尝试验证的唯一数据:Javascript 如何将cuid作为键,值作为具有特定特性的对象来描述和验证对象数组,javascript,json,validation,schema,ajv,Javascript,Json,Validation,Schema,Ajv,我有一个我正在尝试验证的唯一数据: { "name": "Some random name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, "dId": "ewdwe4434"
{
"name": "Some random name",
"blocks": [
{"cj5458hyl0001zss42td3waww": {
"quantity": 9,
"rate": 356.77,
"dId": "ewdwe4434"
}},
{"cj5458hyl0001zss42td3wawu": {
"quantity": 4,
"rate": 356.77,
"dId": "3434ewdwe4434"
}}]
}
这是我现在的作文(无效和不正确):
以及我如何验证它(上下文):
以下是我到目前为止提到的内容:
(一)
(二)
(三)
其他信息:
1) 使用节点8.1.3
2) AJV版本5.2
我知道我需要使用项目数组来描述对象。但是,该对象包含唯一的cuid作为关键点,值作为对象。我想了解如何使用验证嵌套属性和cuid的模式来描述这些数据。我欢迎关于如何最好地处理这些数据的反馈。谢谢你抽出时间 我做了一些自我反省,意识到我所要做的就是利用
patternProperties
关键字,特定于字符串
{
"blockType": {
"additionalProperties": false,
"type": "object",
"properties": {
"name": {
"type": "string"
},
"blocks": {
"type": "array",
"items": {
"type": "object",
"patternProperties": {
"^[a-z][a-z0-9\\-]*$": {
"type": ["object"],
"properties": {
"rate": {
"type": ["integer"]
},
"quantity": {
"type": ["integer"]
},
"dId": {
"type": "string"
}
},
"additionalProperties": false,
"required": ["dId", "quantity", "rate"]
}
}
}
}
},
"required": ["name", "blocks"]
}
}
我可以改进用于验证cuid的正则表达式
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"));
}
};
{
"blockType": {
"additionalProperties": false,
"type": "object",
"properties": {
"name": {
"type": "string"
},
"blocks": {
"type": "array",
"items": {
"type": "object",
"patternProperties": {
"^[a-z][a-z0-9\\-]*$": {
"type": ["object"],
"properties": {
"rate": {
"type": ["integer"]
},
"quantity": {
"type": ["integer"]
},
"dId": {
"type": "string"
}
},
"additionalProperties": false,
"required": ["dId", "quantity", "rate"]
}
}
}
}
},
"required": ["name", "blocks"]
}
}