h3 typebox
v0.6.0
使用 typebox 和 ajv 对 h3 进行 JSON 模式验证。
# Using npm
npm install h3-typebox
# Using yarn
yarn install h3-typebox
# Using pnpm
pnpm install h3-typebox
import { createServer } from 'http'
import { createApp } from 'h3'
import { validateBody , validateQuery , Type } from 'h3-typebox'
const app = createApp ( )
app . use ( '/' , async ( event ) => {
// Validate body
const body = await validateBody ( event , Type . Object ( {
optional : Type . Optional ( Type . String ( ) ) ,
required : Type . Boolean ( ) ,
} ) )
// Validate query
const query = validateQuery ( event , Type . Object ( {
required : Type . String ( ) ,
} ) )
} )
createServer ( app ) . listen ( process . env . PORT || 3000 )
请参阅 TypeBox 文档中如何使用Type
定义架构。
您可以在validateBody
或validateQuery
上定义选项对象。目前支持以下选项:
includeAjvFormats: Boolean
某些格式(例如date
、 date-time
或email
在当前 JSONSchema 草案中指定,但默认情况下不包含在 ajv 中,而是由ajv-formats
包提供。如果需要其中一种格式,您可以在validateBody
或validateQuery
的选项中指定includeAjvFormats: true
如下所示:
// Body
validateBody ( event , schema , { includeAjvFormats : true } )
// Query
validateQuery ( event , schema , { includeAjvFormats : true } )
目前,出于性能和安全原因,仅支持以下扩展格式:
这些可以由自定义架构与Type.Unsafe
方法或内联架构一起使用:
const bodySchema = Type . Object ( {
optional : Type . Optional ( Type . String ( ) ) ,
dateTime : Type . String ( { format : 'date-time' } )
} )
validateBody ( event , bodySchema , { includeAjvFormats : true } )
pnpm install
安装依赖项pnpm dev
运行交互式测试用?
根据麻省理工学院许可发布。