本页还没有译文
本页 50 段还没译成简体中文,下面显示的是英文原文。Validation
还没翻译译自英文(hono.dev)本页 50 段都还没译
要点(模型写的)
模型写的
背景主张方法设置结果局限
Validation
Hono 的薄验证器配合第三方验证器会变得强大
Hono provides only a very thin Validator. However, it can be powerful when combined with a third-party Validator. In addition, the RPC feature allows you to share API specifications with your clients through types.Hono provides only a very thin Validator. However, it can be powerful when combined with a third-party Validator.Hono 验证器很薄,配合第三方验证器很强 RPC 还能通过类型与客户端共享 API 规范Hono 验证器很薄,配合第三方验证器很强Hono 验证器
Manual validator
validator 中间件不依赖第三方库校验请求各部分
First, introduce a way to validate incoming values without using the third-party Validator.First, introduce a way to validate incoming values without using the third-party Validator.手动校验无需第三方验证器即可工作手动校验无需第三方验证器即可工作手动校验
Import validator from hono/validator.Import validator from hono/validator.从 hono/validator 导入 validator从 hono/validator 导入 validatorvalidator 导入
import { validator } from 'hono/validator'To validate form data, specify form as the first argument and a callback as the second argument.
In the callback, validates the value and return the validated values at the end.
The validator can be used as middleware.To validate form data, specify form as the first argument and a callback as the second argument. In the callback, validates the value and return the validated values at the end. The validator can be used as middleware.validator 接收目标和回调,返回校验后的值 它作为中间件运行,处理器只拿到已校验的数据validator 接收目标和回调,返回校验后的值validator 回调
app.post(
'/posts',
validator('form', (value, c) => {
const body = value['body']
if (!body || typeof body !== 'string') {
return c.text('Invalid!', 400)
}
return {
body: body,
}
}),
//...Within the handler, you can get the validated value with c.req.valid('form').Within the handler, you can get the validated value with c.req.valid('form').用 c.req.valid('form') 读取校验后的值用 c.req.valid('form') 读取校验后的值c.req.valid('form')
, (c) => {
const { body } = c.req.valid('form')
// ... do something
return c.json(
{
message: 'Created!',
},
201
)
}Validation targets include json, query, header, param and cookie in addition to form.Validation targets include json, query, header, param and cookie in addition to form.目标包括 json、query、header、param 和 cookie目标包括 json、query、header、param 和 cookie校验目标
Warning
When you validate json or form, the request must contain a matching content-type header (e.g. Content-Type: application/json for json). Otherwise, the request body will not be parsed and you will receive an empty object ({}) as value in the callback.When you validate json or form, the request must contain a matching content-type header (e.g. Content-Type: application/json for json).json 和 form 校验需要匹配的 content-type 头 缺少时请求体不会被解析,回调收到空对象json 和 form 校验需要匹配的 content-type 头content-type 头
It is important to set the content-type header when testing using
app.request().It is important to set the content-type header when testing using
app.request().用 app.request() 测试时要设置 content-type用 app.request() 测试时要设置 content-typeapp.request()
Given an application like this.Given an application like this.示例应用使用直通的 json 验证器示例应用使用直通的 json 验证器直通验证器
const app = new Hono()
app.post(
'/testing',
validator('json', (value, c) => {
// pass-through validator
return value
}),
(c) => {
const body = c.req.valid('json')
return c.json(body)
}
)Your tests can be written like this.Your tests can be written like this.测试中省略该头会返回空对象 加上 Content-Type: application/json 后测试才返回请求体值测试中省略该头会返回空对象空对象
// ❌ this will not work
const res = await app.request('/testing', {
method: 'POST',
body: JSON.stringify({ key: 'value' }),
})
const data = await res.json()
console.log(data) // {}
// ✅ this will work
const res = await app.request('/testing', {
method: 'POST',
body: JSON.stringify({ key: 'value' }),
headers: new Headers({ 'Content-Type': 'application/json' }),
})
const data = await res.json()
console.log(data) // { key: 'value' }Warning
When you validate header, you need to use lowercase name as the key.When you validate header, you need to use lowercase name as the key.header 校验的键必须小写header 校验的键必须小写小写键
If you want to validate the Idempotency-Key header, you need to use idempotency-key as the key.If you want to validate the Idempotency-Key header, you need to use idempotency-key as the key.header 键用小写 idempotency-key 而非 Idempotency-Key 大小写不匹配会让值变为 undefined,中间件总是返回 400header 键用小写 idempotency-key 而非 Idempotency-Keyidempotency-key
// ❌ this will not work
app.post(
'/api',
validator('header', (value, c) => {
// idempotencyKey is always undefined
// so this middleware always return 400 as not expected
const idempotencyKey = value['Idempotency-Key']
if (idempotencyKey == undefined || idempotencyKey === '') {
throw new HTTPException(400, {
message: 'Idempotency-Key is required',
})
}
return { idempotencyKey }
}),
(c) => {
const { idempotencyKey } = c.req.valid('header')
// ...
}
)
// ✅ this will work
app.post(
'/api',
validator('header', (value, c) => {
// can retrieve the value of the header as expected
const idempotencyKey = value['idempotency-key']
if (idempotencyKey == undefined || idempotencyKey === '') {
throw new HTTPException(400, {
message: 'Idempotency-Key is required',
})
}
return { idempotencyKey }
}),
(c) => {
const { idempotencyKey } = c.req.valid('header')
// ...
}
)Multiple validators
多个验证器可分别检查不同的请求部分
You can also include multiple validators to validate different parts of request:You can also include multiple validators to validate different parts of request:链式组合多个验证器,每个校验一个请求部分链式组合多个验证器,每个校验一个请求部分多个验证器
app.post(
'/posts/:id',
validator('param', ...),
validator('query', ...),
validator('json', ...),
(c) => {
//...
}
)With Zod
Zod schema 在 validator 回调中手动进行验证
You can use Zod, one of third-party validators. We recommend using a third-party validator.You can use Zod, one of third-party validators. We recommend using a third-party validator.Zod 是推荐的第三方验证器 它是增强 Hono 薄验证器的若干外部验证器之一Zod 是推荐的第三方验证器Zod
Install from the Npm registry.Install from the Npm registry.从 Npm 仓库安装 zod从 Npm 仓库安装 zodzod 安装
npmyarnpnpmbun
npm i zodyarn add zodpnpm add zodbun add zodImport z from zod.Import z from zod.从 zod 导入 z从 zod 导入 zz 导入
import * as z from 'zod'Write your schema.Write your schema.用 z.object 定义 schema用 z.object 定义 schemaz.object
const schema = z.object({
body: z.string(),
})You can use the schema in the callback function for validation and return the validated value.You can use the schema in the callback function for validation and return the validated value.回调中用 schema.safeParse 并返回 parsed.data 解析失败时返回 401 文本响应而非数据回调中用 schema.safeParse 并返回 parsed.datasafeParse
const route = app.post(
'/posts',
validator('form', (value, c) => {
const parsed = schema.safeParse(value)
if (!parsed.success) {
return c.text('Invalid!', 401)
}
return parsed.data
}),
(c) => {
const { body } = c.req.valid('form')
// ... do something
return c.json(
{
message: 'Created!',
},
201
)
}
)Zod Validator Middleware
zValidator 将 Zod schema 封装为现成中间件
You can use the Zod Validator Middleware to make it even easier.You can use the Zod Validator Middleware to make it even easier.Zod Validator 中间件让 Zod 校验更简单Zod Validator 中间件让 Zod 校验更简单Zod Validator 中间件
npmyarnpnpmbun
npm i @hono/zod-validatoryarn add @hono/zod-validatorpnpm add @hono/zod-validatorbun add @hono/zod-validatorAnd import zValidator.And import zValidator.从 @hono/zod-validator 导入 zValidator从 @hono/zod-validator 导入 zValidatorzValidator 导入
import { zValidator } from '@hono/zod-validator'And write as follows.And write as follows.zValidator 接收目标和一个 Zod schema 处理器随后通过 c.req.valid 读取类型化数据zValidator 接收目标和一个 Zod schemazValidator 用法
const route = app.post(
'/posts',
zValidator(
'form',
z.object({
body: z.string(),
})
),
(c) => {
const validated = c.req.valid('form')
// ... use your validated data
}
)Standard Schema Validator Middleware
sValidator 支持任意 Standard Schema 库并保持一致类型
Standard Schema is a specification that provides a common interface for TypeScript validation libraries. It was created by the maintainers of Zod, Valibot, and ArkType to allow ecosystem tools to work with any validation library without needing custom adapters.Standard Schema is a specification that provides a common interface for TypeScript validation libraries. It was created by the maintainers of Zod, Valibot, and ArkType to allow ecosystem tools to work with any validation library without needing custom adapters.Standard Schema 是 TS 校验库的通用接口 它由 Zod、Valibot、ArkType 维护者创建,工具无需自定义适配器Standard Schema 是 TS 校验库的通用接口Standard Schema
The Standard Schema Validator Middleware lets you use any Standard Schema-compatible validation library with Hono, giving you the flexibility to choose your preferred validator while maintaining consistent type safety.The Standard Schema Validator Middleware lets you use any Standard Schema-compatible validation library with Hono, giving you the flexibility to choose your preferred validator while maintaining consistent type safety.sValidator 支持任意 Standard Schema 库并保证类型安全 你可自选验证器,Hono 仍保持一致的类型安全sValidator 支持任意 Standard Schema 库并保证类型安全sValidator
npmyarnpnpmbun
npm i @hono/standard-validatoryarn add @hono/standard-validatorpnpm add @hono/standard-validatorbun add @hono/standard-validatorImport sValidator from the package:Import sValidator from the package:从 @hono/standard-validator 导入 sValidator从 @hono/standard-validator 导入 sValidatorsValidator 导入
import { sValidator } from '@hono/standard-validator'With Zod
Zod 通过 Standard Schema 与 sValidator 配合使用
You can use Zod with the Standard Schema validator:You can use Zod with the Standard Schema validator:Zod schema 可直接传给 sValidator 处理器通过 c.req.valid 读取校验后的 jsonZod schema 可直接传给 sValidatorZod schema
npmyarnpnpmbun
npm i zodyarn add zodpnpm add zodbun add zodimport * as z from 'zod'
import { sValidator } from '@hono/standard-validator'
const schema = z.object({
name: z.string(),
age: z.number(),
})
app.post('/author', sValidator('json', schema), (c) => {
const data = c.req.valid('json')
return c.json({
success: true,
message: `${data.name} is ${data.age}`,
})
})With Valibot
轻量的 Zod 替代品 Valibot 可与 sValidator 配合
Valibot is a lightweight alternative to Zod with a modular design:Valibot is a lightweight alternative to Zod with a modular design:Valibot schema 以同样方式配合 sValidatorValibot schema 以同样方式配合 sValidatorValibot schema
npmyarnpnpmbun
npm i valibotyarn add valibotpnpm add valibotbun add valibotimport * as v from 'valibot'
import { sValidator } from '@hono/standard-validator'
const schema = v.object({
name: v.string(),
age: v.number(),
})
app.post('/author', sValidator('json', schema), (c) => {
const data = c.req.valid('json')
return c.json({
success: true,
message: `${data.name} is ${data.age}`,
})
})With ArkType
ArkType 的 TypeScript 原生语法可与 sValidator 配合
ArkType offers TypeScript-native syntax for runtime validation:ArkType offers TypeScript-native syntax for runtime validation:ArkType 的 type 语法可配合 sValidatorArkType 的 type 语法可配合 sValidatorArkType 语法
npmyarnpnpmbun
npm i arktypeyarn add arktypepnpm add arktypebun add arktypeimport { type } from 'arktype'
import { sValidator } from '@hono/standard-validator'
const schema = type({
name: 'string',
age: 'number',
})
app.post('/author', sValidator('json', schema), (c) => {
const data = c.req.valid('json')
return c.json({
success: true,
message: `${data.name} is ${data.age}`,
})
})