美文网首页
json Schema + typeScript 实战

json Schema + typeScript 实战

作者: Maco_wang | 来源:发表于2021-01-20 14:49 被阅读0次
<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src
import Ajv, { JSONSchemaType, DefinedError } from 'ajv'
import ajvErrors from 'ajv-errors'
export default defineComponent({
  components: {
    HelloWorld
  },
  setup: function () {
    const ajv = new Ajv({ allErrors: true })
    ajvErrors(ajv)
    interface Foo {
      foo?: {
        id: 1 | 2 ;
      };
    }

    type MyData = Foo;
    type JSONSchemaMyType = JSONSchemaType<Required<MyData>>; // 需要先转换为必须元素
    const schema: JSONSchemaMyType = {
      type: 'object',
      properties: {
        foo: {
          type: 'object',
          properties: {
            id: {
              type: 'number',
              enum: [1, 2],
              errorMessage: {
                type: 'id数据类型错误'
              }
            }
          },
          required: ['id'],
          errorMessage: {
            type: 'foo数据格式错误',
            required: {
              id: 'id参数缺失'
            }
          }
        }
      },
      additionalProperties: false,
      required: ['foo']
    }
    const validate = ajv.compile(schema)
    const data: any = {
      foo: {}
    }
    if (validate(data)) {
      // data is MyData here
      console.log(data.foo)
    } else {
      console.log(validate.errors)
      // The type cast is needed to allow user-defined keywords and errors
      // You can extend this type to include your error types as needed.
      for (const err of validate.errors as DefinedError[]) {
        switch (err.keyword) {
          case 'minimum':
            // err type is narrowed here to have "minimum" error params properties
            break
        }
      }
    }
  }
})
</script>

相关文章

网友评论

      本文标题:json Schema + typeScript 实战

      本文链接:https://www.haomeiwen.com/subject/ctekzktx.html