ajv 使用
在使用前,需要知道 json-schema
是什么。
json-schema
json-schema 是一個用來描述json
數據格式。
ajv
ajv
是一個校驗 json-schema
的數據格式工具(也有其他的,這里具體講解 ajv)。
ajv 引入
import Ajv from "ajv";
const options = {}; // 具體的配置
const ajv = new Ajv(options); // 某些情況下,需要改為 new Ajv.default()
// 開啟校驗
const isValid = ajv.validate(schemas, data); // schemas 具體配置,data數據
if (!iaValid) {
throw new Error(ajv.errorsText());
}
json-schema
默認含有下面 6 種數據結構string
,number
, object
,array
,boolean
,null
。
通過 ajv-keywords 可以進行擴展更多類型。
同時支持自定義類型
class MyClass {}
const instanceofDef = require("ajv-keywords/dist/definitions/instanceof");
instanceofDef.CONSTRUCTORS.MyClass = MyClass;
ajv.validate({ instanceof: "MyClass" }, new MyClass()); // true
文檔太枯燥,這些基本知識又不想炒閑飯式地再敘述一遍,舉幾個示例吧,簡潔明了,走起。
基本類型
// 規定校驗類型
const schema = {
type: "object",
properties: {
// 屬性
get: {
type: "object", // 類型
properties: {
url: {
type: "string",
},
method: {
type: "string",
},
},
required: ["url"], // 必須包含 url 屬性
},
},
};
// 具體數據
const data = {
get: {
url: "http://localhost:8080/get",
},
};
重復代碼塊如何處理
// 規定校驗類型
const schema = {
type: 'object',
properties: { // 屬性
get: {
+ $id: '#getType',
type: 'object', // 類型
properties: {
url: {
type: 'string'
},
method: {
type: 'string'
},
},
required: ['url'] // 必須包含 url 屬性
},
put: {
- type: 'object', // 類型
- properties: {
- url: {
- type: 'string'
- },
- method: {
- type: 'string'
- },
- },
- required: ['url'] // 必須包含 url 屬性
+ $ref: '#getType' // 關聯上面get,與之屬性保持一致
},
delete: {
$ref: '#getType'
}
}
}
不支持的格式如何處理
由於 json-schemas
不支持 js
里復雜數據類型的具體類型,比如 function
, date
...,因而需要引入 ajv-keywords 進行額外補充,但是類型只支持上面列出的類型。
import Ajv from "ajv";
import AjvKeywords from "ajv-keywords";
const ajv = new Ajv();
AjvKeywords(ajv, ["typeof", "instanceof"]); // 除了 type 定義類型外,還可以通過 typeof,instanceof
// 規定校驗類型
const schema = {
type: "object",
properties: {
// 屬性
get: {
type: "object", // 類型
properties: {
url: {
type: "string",
},
method: {
type: "string",
},
},
required: ["url"], // 必須包含 url 屬性
},
getMethod: {
instanceof: "Function", // typeof 類似,只是支持的類型不同
},
list: {
instanceof: ["Function", "Array"],
},
},
};
const data = {
get: {
url: "http://localhost:8080/get",
},
getMethod() {},
list: [],
};
通過上面的方式,便可以對日常使用 json
格式的數據進行校驗,保證在處理數據前,拿到的數據是有效的,可以避免很多繁瑣的數據格式校驗,而且也有了一個統一的規則。