使用ajv校验json-schema数据格式

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 格式的数据进行校验,保证在处理数据前,拿到的数据是有效的,可以避免很多繁琐的数据格式校验,而且也有了一个统一的规则。

参考链接

原文地址:https://www.cnblogs.com/sinosaurus/p/14264567.html