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

原文链接: 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

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

up-aed20173baa6a8b2c0ce5f8746dbf451cd1.png

/**
 * 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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值