Model is a class to describe and check data structure. To describe data structure you should use strategies and nested models.
Strategies are small functions that check a given value for type and, if the type is wrong, tries to convert it.
There are 4 base strategies for types, but you can create more specific strategies (e.g. for date, multiple fields etc.):
numberStrategy
: checks value for Number
, if not, will convert in to Number
if the result is not NaN
.
stringStrategy
: checks value for String
and tries to convert only if value is Number
.
booleanStrategy
: checks value for Boolean
and tries to convert only if value is either 'true'
or 'false'
arrayStrategy
: array is not primitive, you could check array for certain item type, or any type: arrayStrategy.of(stringStrategy)
, arrayStrategy.any
Model takes into constructor a structure with strategies, like that:
{
phone: stringStrategy,
list: arrayStrategy.any
}
Model also should has a name, if error occurs you will know which model and request you should check:
new Model({}, 'CatalogModel')
Model structure is an object with fields, that can be either strategy, object with more configuration or another model:
{
phone: stringStrategy,
list: {
required: true,
strategy: arrayStrategy.any
},
complex: new Model({ complexName: stringStrategy })
}
By default when checking value model skips missing fields, if you need some field to be required you can do it by passing an Object with required
key and strategy
to check:
{
list: {
required: true,
strategy: arrayStrategy.any
}
}
To create a model you will need a base class and strategies:
import Model from '@/services/Model.class'
import { stringStrategy, arrayStrategy } from '@/services/Strategies'
const MenuModel = new Model({
phone: stringStrategy,
list: arrayStrategy.any
})
export default MenuModel
Model has checkValue
method with value argument, it returns checked and normalized value:
const checkedData = MenuModel.checkValue(data)