AlfieriChou / alfierichou.github.io

AlfieriChou的博客
https://alfierichou.com
4 stars 0 forks source link

deno使用ajv校验 #23

Open AlfieriChou opened 2 years ago

AlfieriChou commented 2 years ago
  1. 每次都编译json-schema校验,并且能拿到校验报错详细信息
import Ajv from 'https://esm.sh/ajv@8.6.1'

const schema = {
  type: 'object',
  properties: {
    a: {type: 'string' },
    b: { type: 'number' }
  },
  required: ['a']
}

const ajv: Ajv = new Ajv()

const start = async (): Promise<any> => {
  const data: boolean = ajv.validate(schema, { a: '1', b: '2' })
  console.log('---', data, ajv.errors)
}

start()
  1. 预先编译json-schema然后再校验,拿不到报错详细信息
import Ajv, { ValidateFunction } from 'https://esm.sh/ajv@8.6.1'

const schema = {
  type: 'object',
  properties: {
    a: {type: 'string' },
    b: { type: 'number' }
  },
  required: ['a']
}

const ajv: Ajv = new Ajv()
const validate: ValidateFunction = ajv.compile(schema)

const start = async (): Promise<any> => {
  const data: boolean = validate({ a: '1', b: '2' })
  console.log('---', data, ajv.errors)
}

start()