主题
类型
¥Type
以下是使用 Elysia.t
编写验证类型的常见模式。
¥Here's a common patterns for writing validation types using Elysia.t
.
原始类型
¥Primitive Type
TypeBox API 的设计围绕 TypeScript 类型,并且与 TypeScript 类型类似。
¥The TypeBox API is designed around and is similar to TypeScript types.
有很多熟悉的名称和行为与 TypeScript 对应项相交叉,例如 String、Number、Boolean 和 Object,以及更高级的功能,例如 Intersect、KeyOf 和 Tuple,以实现多功能性。
¥There are many familiar names and behaviors that intersect with TypeScript counterparts, such as String, Number, Boolean, and Object, as well as more advanced features like Intersect, KeyOf, and Tuple for versatility.
如果你熟悉 TypeScript,那么创建 TypeBox 模式的行为与编写 TypeScript 类型相同,只是它在运行时提供实际的类型验证。
¥If you are familiar with TypeScript, creating a TypeBox schema behaves the same as writing a TypeScript type, except it provides actual type validation at runtime.
要创建你的第一个 schema,请从 Elysia 导入 Elysia.t 并从最基本的类型开始:
¥To create your first schema, import Elysia.t from Elysia and start with the most basic type:
typescript
import { Elysia, t } from 'elysia'
new Elysia()
.post('/', ({ body }) => `Hello ${body}`, {
body: t.String()
})
.listen(3000)
此代码告诉 Elysia 验证传入的 HTTP 正文,确保正文为字符串。如果是字符串,则允许其流经请求管道和处理程序。
¥This code tells Elysia to validate an incoming HTTP body, ensuring that the body is a string. If it is a string, it will be allowed to flow through the request pipeline and handler.
如果形状不匹配,它将向 错误生命周期 抛出错误。
¥If the shape doesn't match, it will throw an error into the Error Life Cycle.
基本类型
¥Basic Type
TypeBox 提供与 TypeScript 类型具有相同行为的基本原始类型。
¥TypeBox provides basic primitive types with the same behavior as TypeScript types.
下表列出了最常见的基本类型:
¥The following table lists the most common basic types:
TypeBox | TypeScript |
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
Elysia 扩展了 TypeBox 的所有类型,允许你在 Elysia 中使用 TypeBox 的大部分 API。
¥Elysia extends all types from TypeBox, allowing you to reference most of the API from TypeBox for use in Elysia.
有关 TypeBox 支持的其他类型,请参阅 TypeBox 的类型。
¥See TypeBox's Type for additional types supported by TypeBox.
属性
¥Attribute
TypeBox 可以接受基于 JSON Schema 7 规范的参数,以实现更全面的行为。
¥TypeBox can accept arguments for more comprehensive behavior based on the JSON Schema 7 specification.
TypeBox | TypeScript |
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
有关每个属性的更多解释,请参阅 JSON Schema 7 规范。
¥See JSON Schema 7 specification for more explanation of each attribute.
荣誉提名
¥Honorable Mentions
以下是在创建架构时经常发现有用的常见模式。
¥The following are common patterns often found useful when creating a schema.
Union
允许 t.Object
中的字段具有多种类型。
¥Allows a field in t.Object
to have multiple types.
TypeBox | TypeScript | Value |
typescript
| typescript
|
|
可选
¥Optional
允许 t.Object
中的字段为未定义或可选。
¥Allows a field in t.Object
to be undefined or optional.
TypeBox | TypeScript | Value |
typescript
| typescript
| typescript
|
部分
¥Partial
允许 t.Object
中的所有字段为可选。
¥Allows all fields in t.Object
to be optional.
TypeBox | TypeScript | Value |
typescript
| typescript
| typescript
|
Elysia 类型
¥Elysia Type
Elysia.t
基于 TypeBox,并预先配置了服务器使用,提供了服务器端验证中常见的其他类型。
¥Elysia.t
is based on TypeBox with pre-configuration for server usage, providing additional types commonly found in server-side validation.
你可以在 elysia/type-system
中找到 Elysia 类型的所有源代码。
¥You can find all the source code for Elysia types in elysia/type-system
.
以下是 Elysia 提供的类型:
¥The following are types provided by Elysia:
UnionEnum
UnionEnum
允许将值设置为指定的值之一。
¥UnionEnum
allows the value to be one of the specified values.
typescript
t.UnionEnum(['rapi', 'anis', 1, true, false])
文件
¥File
单个文件,通常用于文件上传验证。
¥A singular file, often useful for file upload validation.
typescript
t.File()
File 扩展了基础架构的属性,并添加了以下属性:
¥File extends the attributes of the base schema, with additional properties as follows:
type
指定文件的格式,例如图片、视频或音频。
¥Specifies the format of the file, such as image, video, or audio.
如果提供的是数组,它将尝试验证任何格式是否有效。
¥If an array is provided, it will attempt to validate if any of the formats are valid.
typescript
type?: MaybeArray<string>
minSize
文件的最小大小。
¥Minimum size of the file.
接受字节数或文件单位后缀:
¥Accepts a number in bytes or a suffix of file units:
typescript
minSize?: number | `${number}${'k' | 'm'}`
maxSize
文件的最大大小。
¥Maximum size of the file.
接受字节数或文件单位后缀:
¥Accepts a number in bytes or a suffix of file units:
typescript
maxSize?: number | `${number}${'k' | 'm'}`
文件单元后缀:
¥File Unit Suffix:
以下是文件单元的规范:m:兆字节(1048576 字节)k:千字节 (1024 字节)
¥The following are the specifications of the file unit: m: MegaByte (1048576 byte) k: KiloByte (1024 byte)
文件
¥Files
扩展自 文件,但增加了对单个字段中文件数组的支持。
¥Extends from File, but adds support for an array of files in a single field.
typescript
t.Files()
File 扩展了基础架构、数组和 File 的属性。
¥Files extends the attributes of the base schema, array, and File.
Cookie
从 Object 类型扩展而来的 Cookie Jar 的对象类表示。
¥Object-like representation of a Cookie Jar extended from the Object type.
typescript
t.Cookie({
name: t.String()
})
Cookie 扩展了 对象 和 Cookie 的属性,并添加了以下属性:
¥Cookie extends the attributes of Object and Cookie with additional properties as follows:
secrets
用于签署 Cookie 的密钥。
¥The secret key for signing cookies.
接受字符串或字符串数组。
¥Accepts a string or an array of strings.
typescript
secrets?: string | string[]
如果提供的是数组,将使用 密钥轮换。新签名的值将使用第一个密钥作为密钥。
¥If an array is provided, Key Rotation will be used. The newly signed value will use the first secret as the key.
可空值
¥Nullable
允许值为 null 但不允许为未定义。
¥Allows the value to be null but not undefined.
typescript
t.Nullable(t.String())
MaybeEmpty
允许值为 null 和未定义。
¥Allows the value to be null and undefined.
typescript
t.MaybeEmpty(t.String())
更多信息,你可以在 elysia/type-system
中找到类型系统的完整源代码。
¥For additional information, you can find the full source code of the type system in elysia/type-system
.
表单
¥Form
t.Object
的语法糖,支持验证 form(FormData)的返回值。
¥A syntax sugar our t.Object
with support for verifying return value of form (FormData).
typescript
t.FormData({
someValue: t.File()
})
UInt8Array
接受可解析为 Uint8Array
的缓冲区。
¥Accepts a buffer that can be parsed into a Uint8Array
.
typescript
t.UInt8Array()
当你想要接受可解析为 Uint8Array
的缓冲区(例如在二进制文件上传中)时,这很有用。它被设计用于使用 arrayBuffer
解析器验证正文,以强制执行正文类型。
¥This is useful when you want to accept a buffer that can be parsed into a Uint8Array
, such as in a binary file upload. It's designed to use for the validation of body with arrayBuffer
parser to enforce the body type.
ArrayBuffer
接受可解析为 ArrayBuffer
的缓冲区。
¥Accepts a buffer that can be parsed into a ArrayBuffer
.
typescript
t.ArrayBuffer()
当你想要接受可解析为 Uint8Array
的缓冲区(例如在二进制文件上传中)时,这很有用。它被设计用于使用 arrayBuffer
解析器验证正文,以强制执行正文类型。
¥This is useful when you want to accept a buffer that can be parsed into a Uint8Array
, such as in a binary file upload. It's designed to use for the validation of body with arrayBuffer
parser to enforce the body type.
ObjectString
接受一个可解析为对象的字符串。
¥Accepts a string that can be parsed into an object.
typescript
t.ObjectString()
当你想要接受一个可以解析为对象但环境不允许的字符串(例如在查询字符串、标头或 FormData 主体中)时,这非常有用。
¥This is useful when you want to accept a string that can be parsed into an object but the environment does not allow it explicitly, such as in a query string, header, or FormData body.
BooleanString
接受可解析为布尔值的字符串。
¥Accepts a string that can be parsed into a boolean.
与 ObjectString 类似,当你想要接受可解析为布尔值的字符串但环境不允许时,这很有用。
¥Similar to ObjectString, this is useful when you want to accept a string that can be parsed into a boolean but the environment does not allow it explicitly.
typescript
t.BooleanString()
数字
¥Numeric
Numeric 接受数字字符串或数字,然后将值转换为数字。
¥Numeric accepts a numeric string or number and then transforms the value into a number.
typescript
t.Numeric()
当传入值是数字字符串(例如路径参数或查询字符串)时,这很有用。
¥This is useful when an incoming value is a numeric string, for example, a path parameter or query string.
Numeric 接受与 数字实例 相同的属性。
¥Numeric accepts the same attributes as Numeric Instance.
Elysia 行为
¥Elysia behavior
Elysia 默认使用 TypeBox。
¥Elysia use TypeBox by default.
然而,为了帮助简化 HTTP 处理。Elysia 拥有一些专用类型,并且与 TypeBox 的行为存在一些差异。
¥However, to help making handling with HTTP easier. Elysia has some dedicated type and have some behavior difference from TypeBox.
可选
¥Optional
要使字段可选,请使用 t.Optional
。
¥To make a field optional, use t.Optional
.
这将允许客户端选择性地提供查询参数。此行为也适用于 body
、headers
。
¥This will allows client to optionally provide a query parameter. This behavior also applied to body
, headers
.
这与 TypeBox 不同,TypeBox 中的可选操作是将对象的字段标记为可选。
¥This is different from TypeBox where optional is to mark a field of object as optional.
typescript
import { Elysia, t } from 'elysia'
new Elysia()
.get('/optional', ({ query }) => query, {
query: t.Optional(
t.Object({
name: t.String()
})
)
})
数字转数字
¥Number to Numeric
默认情况下,当路由模式为 t.Number
时,Elysia 会将其转换为 t.Numeric。
¥By default, Elysia will convert a t.Number
to t.Numeric when provided as route schema.
因为解析的 HTTP 标头、查询和 url 参数始终是字符串。这意味着即使一个值是数字,它也会被视为字符串。
¥Because parsed HTTP headers, query, url parameter is always a string. This means that even if a value is number, it will be treated as string.
Elysia 通过检查字符串值是否类似于数字,然后进行适当的转换来覆盖此行为。
¥Elysia override this behavior by checking if a string value looks like a number then convert it even appropriate.
这仅在用作路由架构时适用,而不是在嵌套的 t.Object
中。
¥This is only applied when it is used as a route schema and not in a nested t.Object
.
ts
import { Elysia, t } from 'elysia'
new Elysia()
.get('/:id', ({ id }) => id, {
params: t.Object({
// Converted to t.Numeric()
id: t.Number()
}),
body: t.Object({
// NOT converted to t.Numeric()
id: t.Number()
})
})
// NOT converted to t.Numeric()
t.Number()
布尔值转布尔字符串
¥Boolean to BooleanString
与 数字转数字 类似
¥Similar to Number to Numeric
任何 t.Boolean
都将转换为 t.BooleanString
。
¥Any t.Boolean
will be converted to t.BooleanString
.
ts
import { Elysia, t } from 'elysia'
new Elysia()
.get('/:id', ({ id }) => id, {
params: t.Object({
// Converted to t.Boolean()
id: t.Boolean()
}),
body: t.Object({
// NOT converted to t.Boolean()
id: t.Boolean()
})
})
// NOT converted to t.BooleanString()
t.Boolean()