@phoenix-cg/model v1.2.12
Models and strategies
Model is a class to describe and check data structure. To describe data structure you should use strategies and nested models.
Strategies
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
enumStrategy: checks for array of objects with different structure, need to pass modelMap and trackProp to diff the models: enumStrategy({ select: selectModel, range: rangeModel }, '_type')
Setting up
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 MenuModelChecking data
Model has checkValue method with value argument, it returns checked and normalized value:
const checkedData = MenuModel.checkValue(data)10 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago