Ajv的使用
Install
npm install ajv
复制代码
Usage
- 定义一个 scheme
const applicationAjvScheme = {
properties: {
data: {
type: 'array',
// required: ['code', 'data', 'message'], // 关键字
items: [
{
type: 'object',
properties: {
count: {
type: 'number',
},
serviceId: {
type: 'string',
},
},
},
],
},
code: {
type: 'number',
},
message: {
type: 'string',
},
},
};
export default applicationAjvScheme;
复制代码
请求的接口为:
http://192.169.3.8:48485/dev-services/get-app-count-by-second-category
- 在文件中使用
import Ajv from 'ajv';
const ajv = new Ajv();
fetchApplicationCount() {
const url = `${env.SERVICE_URL}/dev-services/get-app-count-by-second-category`;
uniFetchNA(url, {})
.then((json) => {
this.setState({ categoryConut: json.data });
console.log(ajv.validate(applicationAjvScheme, json)); // true
})
.catch(handleFetchError);
}
复制代码
接口返回的json数据为:
{
code: 0,
data: [
{
count: 1,
serviceId: '1-3-300',
}
],
message: ''
}
复制代码
如果验证结果为 false
- 找后台说明数据格式不正确