Models validator
Models Validator for Objects.
For example, for JSON-parsed Objects that received from network.
Docs for models:
All model fields describes as:
from
: fieldType
fieldType
can be declared as:
- Simple type:
String
, Number
, Date
, Object
, Array
,...
Array
in this case can contain any elements of any types
- Enum:
new Set(["some_val", 456, "val2"])
(Field can only be "some_val"
or 456
or "val2"
) - Specialized Array (fixed length):
[Number, String, String]
(specialized type of every element in array) - Specialized Array (unlimited length):
{
type: Array,
item: ,
}
- Long type declaration (you can set
optional
param):
{
type: ,
optional: true,
default: "SomeDefaultValue",
from: "some_name",
}
- Nested object declaration:
{
type: Object,
fields: {
}
}
Fields options at long declaration as a result:
type
{{fieldType}}
- Describes the type to which the original field value is converted.optional
[Boolean]
- If it has value "false", field can be not provided.default
[Any value that converts to {{fieldType}}]
- If field is optional
and it's not provided in source data, it will have this value.from
[String]
- Name of field with which it will be searched in the source modelitem
{{long or short fieldType}}
- If field type is Array
, it can be long or short declaring of field type.fields
{Object}
- If field type is Object
, it must be Object with long or short declaring of each object field.
Example model description:
const exampleModel = {
field1: String,
field2: Number,
field3: Object,
field4: Array,
field5: [Number, String],
field6: new Set(["some_val", 456, "val2"]),
field7: {
type: String
},
field8: {
type: Object,
fields: {
field8_1: String,
},
},
field9: {
type: Number,
optional: true,
},
field10: {
type: Array,
item: String,
from: "some_field_10",
},
field11: {
type: Array,
item: {
type: Object,
fields: {
field11_1: String,
}
},
},
}
Example model validation:
const UserModel = {
age: Number,
userName: {
type: [String, String],
from: "user_name",
},
sex: new Set(['male', 'female']),
children: {
type: Array,
optional: true,
item: {
type: Object,
fields: {
name: String,
age: Number,
}
}
}
}
const response = fetch('/user', {method: 'GET'});
const data = validateModel(UserModel, await response.text());
For more examples you can see file with tests validateModel.test.js