欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

typescript-json-schema 和 ajv 可检测数据是否符合指定的 ts 类型

最编程 2024-03-16 17:54:53
...
3月16日,北京源创会 —— “数据库,2024 开炫”

 

原文链接: typescript-json-schema 和 ajv 检测数据是否符合指定的ts类型

上一篇: regl 视频播放 用canvas展示video中的内容

下一篇: pako 压缩lottie动效资源方案

https://ajv.js.org/

https://github.com/YousefED/typescript-json-schema

 

把之前图片对象的类型导出来

npx typescript-json-schema './src/t.ts' 'ImageItem'   -o './schema.json' --required=true  --strictNullChecks

 

支持注释的方式, 表示这个类型不能有多余的字段,  默认只有少字段报错, 多余的话不报错

/**
 * The additionalProperties annotation should be ignored
 * @additionalProperties false
 */

 

用ajv执行检测

import Ajv from "ajv";

const schema = {
  $schema: "http://json-schema.org/draft-07/schema#",
  additionalProperties: false,
  definitions: {
    ImageType: {
      enum: ["jpg", "png", "webp"],
      type: "string",
    },
  },
  description: "The additionalProperties annotation should be ignored",
  properties: {
    bottom: {
      type: "number",
    },
    degree: {
      type: "number",
    },
    fileType: {
      $ref: "#/definitions/ImageType",
    },
    filters: {
      items: {
        enum: ["bigGaussian", "canny", "grayscale", "invert", "mirror"],
        type: "string",
      },
      type: "array",
    },
    height: {
      type: "number",
    },
    id: {
      type: "string",
    },
    index: {
      type: "number",
    },
    left: {
      type: "number",
    },
    loading: {
      type: "boolean",
    },
    name: {
      type: "string",
    },
    random: {
      type: "string",
    },
    right: {
      type: "number",
    },
    size: {
      type: ["string", "number"],
    },
    specialLR: {
      type: "boolean",
    },
    specialTB: {
      type: "boolean",
    },
    top: {
      type: "number",
    },
    width: {
      type: "number",
    },
  },
  required: [
    "bottom",
    "degree",
    "fileType",
    "filters",
    "height",
    "id",
    "index",
    "left",
    "loading",
    "name",
    "random",
    "right",
    "size",
    "specialLR",
    "specialTB",
    "top",
    "width",
  ],
  type: "object",
};

const ajv = new Ajv({ allErrors: true, jsonPointers: true });

const validate = ajv.compile(schema);

const json = {
  width: 1,
  width222: 1,
  height: 1,
  degree: 1,
  name: "string",
  specialLR: true,
  specialTB: true,
  size: 1,
  id: "string", // md5
  top: 1, //上下左右分割线
  bottom: 1,
  left: 1,
  right: 1,
  fileType: "png", // 图片类型
  index: 1, // 图片所在第几个, 一般和数组中的位置一一对应
  filters: [], // 滤镜数组, 有顺序
  random: "1", // 唯一id
  loading: false, // 是否正在被处理
};
const valid = validate(json);
if (!valid) {
  console.log(validate.errors);
}