json-model-validator
v1.0.0-alpha.1
Published
json validator and transfer
Downloads
2
Readme
json-model-validator
轻量级请求数据检查&格式化工具
usage
安装
npm i json-model-validator
声明 json 模型
import {
JSONModel,
JSONMember,
FIELD_TYPE,
} from 'json-model-validator';
@JSONModel
class SubSubModel {
@JSONMember(FIELD_TYPE.ANY)
subsub: any;
}
@JSONModel
class TestSubModel {
@JSONMember(FIELD_TYPE.ANY)
uuid: any;
@JSONMember(SubSubModel)
sub: SubSubModel;
}
@JSONModel
class TestModel {
@JSONMember(FIELD_TYPE.NUMBER)
uid: any;
@JSONMember(FIELD_TYPE.STRING)
code: string;
@JSONMember(FIELD_TYPE.ARRAY(String), (cateIds) => cateIds.split(','))
cateIds: string;
@JSONMember(TestSubModel)
t: TestSubModel;
}
校验请求或接口数据是否符合格式
import JSONValidator from 'json-model-validator',
console.log(JSONValidator(TestModel, { uid: '0', cateIds: '0,1', t: { uuid: 0 } }));
// throw ValidationError, errorList ['待检查的数据 data.t.sub 应为 SubSubModel 对象,当前值为 undefined']
console.log(JSONValidator(TestModel, { uid: [0], cateIds: '0,1', t: { sub: { subsub: 0 } } }));
// {"t":{"sub":{"subsub":0},"uuid":""},"uid":0,"cateIds":["0","1"]}