I have a unique data that I am attempting to validate:
{
"name": "Some random name",
"blocks": [
{"cj5458hyl0001zss42td3waww": {
"quantity": 9,
"rate": 356.77,
"dId": "ewdwe4434"
}},
{"cj5458hyl0001zss42td3wawu": {
"quantity": 4,
"rate": 356.77,
"dId": "3434ewdwe4434"
}}]
}
Here is the composition that I have right now (invalid and incorrect):
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"]
};
and how I am validating it (for context):
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"));
}
};
Here is what I have referenced so far:
1) AJV schema validation for array of objects
2) https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md
3) https://spacetelescope.github.io/understanding-json-schema/reference/object.html
Additional information:
1) Using Node 8.1.3
2) AJV version 5.2
I know that I need to use an array of items to describe the object. However the object contains a unique cuid as a key and the value as a an object. I would like to understand how to describe this data using such a schema that validates the nested properties and the cuid. I welcome feedback on how to best approach this data. Thank you for your time.