I have a customized data set that requires validation:
{
"name": "Some unique name",
"blocks": [
{"cj5458hyl0001zss42td3waww": {
"quantity": 9,
"rate": 356.77,
"dId": "ewdwe4434"
}},
{"cj5458hyl0001zss42td3wawu": {
"quantity": 4,
"rate": 356.77,
"dId": "3434ewdwe4434"
}}]
}
My current structure (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"]
};
Validation process (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"));
}
};
References used:
1) AJV schema validation for array of objects
2) https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md
3)
Additional details:
1) Operating on Node 8.1.3
2) Using AJV version 5.2
I realize I need to employ an array of items to define the object. However, my object comprises a distinct cuid as a key and an object as its value. Any advice on accurately describing this dataset using a schema that validates both the nested properties and the cuid will be appreciated. Thank you for your time.