Skip to content

配置

¥Config

Elysia 具有可配置的行为,允许我们自定义其功能的各个方面。

¥Elysia comes with a configurable behavior, allowing us to customize various aspects of its functionality.

我们可以使用构造函数定义配置。

¥We can define a configuration by using a constructor.

ts
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
({
prefix
: '/v1',
normalize
: true
})

adapter

自 1.1.11 起

¥Since 1.1.11

用于在不同环境中使用 Elysia 的运行时适配器。

¥Runtime adapter for using Elysia in different environments.

默认根据环境使用合适的适配器。

¥Default to appropriate adapter based on the environment.

ts
import { Elysia, t } from 'elysia'
import { BunAdapter } from 'elysia/adapter/bun'

new Elysia({
	adapter: BunAdapter
})

aot

自 0.4.0 起

¥Since 0.4.0

提前编译。

¥Ahead of Time compilation.

Elysia 内置了 JIT "compiler",可以处理 优化性能

¥Elysia has a built-in JIT "compiler" that can optimize performance.

ts
import { 
Elysia
} from 'elysia'
new
Elysia
({
aot
: true
})

禁用提前编译

¥Disable Ahead of Time compilation

选项 - @default false

¥Options - @default false

  • true - 启动服务器前预编译每个路由

  • false - 完全禁用 JIT。启动速度更快,且不影响性能。

detail

为实例的所有路由定义 OpenAPI 模式。

¥Define an OpenAPI schema for all routes of an instance.

此模式将用于为实例的所有路由生成 OpenAPI 文档。

¥This schema will be used to generate OpenAPI documentation for all routes of an instance.

ts
import { 
Elysia
} from 'elysia'
new
Elysia
({
detail
: {
hide
: true,
tags
: ['elysia']
} })

encodeSchema

在将响应返回给客户端之前,使用自定义 Encode 处理自定义 t.Transform 模式。

¥Handle custom t.Transform schema with custom Encode before returning the response to client.

这使我们能够在将响应发送到客户端之前为你的数据创建自定义编码函数。

¥This allows us to create custom encode function for your data before sending response to the client.

ts
import { Elysia, t } from 'elysia'

new Elysia({ encodeSchema: true })

选项 - @default true

¥Options - @default true

  • true - 向客户端发送响应前运行 Encode

  • false - 完全跳过 Encode

name

定义用于调试和 插件数据去重 的实例名称

¥Define a name of an instance which is used for debugging and Plugin Deduplication

ts
import { 
Elysia
} from 'elysia'
new
Elysia
({
name
: 'service.thing'
})

nativeStaticResponse

自 1.1.11 起

¥Since 1.1.11

使用优化函数处理每个相应运行时的内联值。

¥Use an optimized function for handling inline value for each respective runtime.

ts
import { 
Elysia
} from 'elysia'
new
Elysia
({
nativeStaticResponse
: true
})

示例

¥Example

如果在 Bun 上启用,Elysia 会在 Bun.serve.static 中插入内联值,以提高静态值的性能。

¥If enabled on Bun, Elysia will insert inline value into Bun.serve.static improving performance for static value.

ts
import { Elysia } from 'elysia'

// This
new Elysia({
	nativeStaticResponse: true
}).get('/version', 1)

// is an equivalent to
Bun.serve({
	static: {
		'/version': new Response(1)
	}
})

normalize

自 1.1.0 起

¥Since 1.1.0

Elysia 是否应将字段强制转换为指定的模式。

¥Whether Elysia should coerce field into a specified schema.

ts
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
({
normalize
: true
})

当在输入和输出中发现未在架构中指定的未知属性时,Elysia 应如何处理该字段?

¥When unknown properties that are not specified in schema are found on either input and output, how should Elysia handle the field?

选项 - @default true

¥Options - @default true

  • true:Elysia 将使用 精确镜像 将字段强制转换为指定的模式。

  • typebox:Elysia 将使用 TypeBox 的 Value.Clean 将字段强制转换为指定的模式。

  • false:如果请求或响应包含相应处理程序的架构中未明确允许的字段,Elysia 将引发错误。

precompile

自 1.0.0 起

¥Since 1.0.0

Elysia 是否应该在启动服务器之前提前 预编译所有路由

¥Whether Elysia should precompile all routes ahead of time before starting the server.

ts
import { 
Elysia
} from 'elysia'
new
Elysia
({
precompile
: true
})

选项 - @default false

¥Options - @default false

  • true:启动服务器前在所有路由上运行 JIT

  • false:按需动态编译路由

建议将其保留为 false

¥It's recommended to leave it as false.

prefix

为实例的所有路由定义前缀

¥Define a prefix for all routes of an instance

ts
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
({
prefix
: '/v1'
})

定义前缀后,所有路由都将以给定值作为前缀。

¥When prefix is defined, all routes will be prefixed with the given value.

示例

¥Example

ts
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
({
prefix
: '/v1' }).
get
('/name', 'elysia') // Path is /v1/name

sanitize

一个函数或一个函数数组,在验证时调用并拦截每个 t.String 请求。

¥A function or an array of function that calls and intercepts on every t.String while validation.

允许我们读取字符串并将其转换为新值。

¥Allowing us to read and transform a string into a new value.

ts
import { Elysia, t } from 'elysia'

new Elysia({
	sanitize: (value) => Bun.escapeHTML(value)
})

seed

定义一个用于生成实例校验和的值,用于 插件数据去重

¥Define a value which will be used to generate checksum of an instance, used for Plugin Deduplication

ts
import { 
Elysia
} from 'elysia'
new
Elysia
({
seed
: {
value
: 'service.thing'
} })

值可以是任何类型,不限于字符串、数字或对象。

¥The value could be any type not limited to string, number, or object.

strictPath

Elysia 是否应严格处理路径。

¥Whether should Elysia handle path strictly.

根据 RFC 3986,路径应该严格等于路由中定义的路径。

¥According to RFC 3986, a path should be strictly equal to the path defined in the route.

ts
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
({
strictPath
: true })

选项 - @default false

¥Options - @default false

  • true - 严格遵循 RFC 3986 进行路径匹配

  • false - 支持后缀 '/',反之亦然。

示例

¥Example

ts
import { 
Elysia
,
t
} from 'elysia'
// Path can be either /name or /name/ new
Elysia
({
strictPath
: false }).
get
('/name', 'elysia')
// Path can be only /name new
Elysia
({
strictPath
: true }).
get
('/name', 'elysia')

serve

自定义 HTTP 服务器行为。

¥Customize HTTP server behavior.

Bun 服务配置。

¥Bun serve configuration.

ts
import { Elysia } from 'elysia'

new Elysia({
	serve: {
		hostname: 'elysiajs.com',
		tls: {
			cert: Bun.file('cert.pem'),
			key: Bun.file('key.pem')
		}
	},
})

此配置扩展了 Bun 服务 APIBun TLS

¥This configuration extends Bun Serve API and Bun TLS

示例:最大主体大小

¥Example: Max body size

我们可以通过在 serve 配置中设置 serve.maxRequestBodySize 来设置最大正文大小。

¥We can set the maximum body size by setting serve.maxRequestBodySize in the serve configuration.

ts
import { Elysia } from 'elysia'

new Elysia({
	serve: {
		maxRequestBodySize: 1024 * 1024 * 256 // 256MB
	}
})

默认情况下,最大请求体大小为 128MB(1024 * 1024 * 128)。定义主体大小限制。

¥By default the maximum request body size is 128MB (1024 * 1024 * 128). Define body size limit.

ts
import { Elysia } from 'elysia'

new Elysia({
	serve: {
		// Maximum message size (in bytes)
	    maxPayloadLength: 64 * 1024,
	}
})

示例:HTTPS / TLS

¥Example: HTTPS / TLS

我们可以通过传入 key 和 cert 的值来启用 TLS(SSL 的后继者);两者都是启用 TLS 所必需的。

¥We can enable TLS (known as successor of SSL) by passing in a value for key and cert; both are required to enable TLS.

ts
import { Elysia, file } from 'elysia'

new Elysia({
	serve: {
		tls: {
			cert: file('cert.pem'),
			key: file('key.pem')
		}
	}
})

示例:增加超时时间

¥Example: Increase timeout

我们可以通过在 serve 配置中设置 serve.idleTimeout 来增加空闲超时时间。

¥We can increase the idle timeout by setting serve.idleTimeout in the serve configuration.

ts
import { Elysia } from 'elysia'

new Elysia({
	serve: {
		// Increase idle timeout to 30 seconds
		idleTimeout: 30
	}
})

默认情况下,空闲超时时间为 10 秒(在 Bun 上)。

¥By default the idle timeout is 10 seconds (on Bun).


serve

HTTP 服务器配置。

¥HTTP server configuration.

Elysia 扩展了 Bun 配置,该配置支持开箱即用的 TLS,由 BoringSSL 提供支持。

¥Elysia extends Bun configuration which supports TLS out of the box, powered by BoringSSL.

有关可用配置,请参阅 serve.tls

¥See serve.tls for available configuration.

serve.hostname

@default 0.0.0.0

设置服务器监听的主机名

¥Set the hostname which the server listens on

serve.id

使用 ID 唯一标识服务器实例

¥Uniquely identify a server instance with an ID

此字符串将用于热重载服务器,而不会中断待处理的请求或 WebSocket。如果未提供,则会生成一个值。要禁用热重载,请将此值设置为 null

¥This string will be used to hot reload the server without interrupting pending requests or websockets. If not provided, a value will be generated. To disable hot reloading, set this value to null.

serve.idleTimeout

@default 10 (10 seconds)

默认情况下,Bun 将空闲超时设置为 10 秒,这意味着如果请求在 10 秒内未完成,它将被中止。

¥By default, Bun set idle timeout to 10 seconds, which means that if a request is not completed within 10 seconds, it will be aborted.

serve.maxRequestBodySize

@default 1024 * 1024 * 128 (128MB)

设置请求主体的最大大小(以字节为单位)

¥Set the maximum size of a request body (in bytes)

serve.port

@default 3000

监听端口

¥Port to listen on

serve.rejectUnauthorized

@default NODE_TLS_REJECT_UNAUTHORIZED environment variable

如果设置为 false,则接受任何证书。

¥If set to false, any certificate is accepted.

serve.reusePort

@default true

如果需要设置 SO_REUSEPORT 标志

¥If the SO_REUSEPORT flag should be set

这允许多个进程绑定到同一端口,这对于负载平衡非常有用。

¥This allows multiple processes to bind to the same port, which is useful for load balancing

此配置会被 Elysia 覆盖并默认启用。

¥This configuration is override and turns on by default by Elysia

serve.unix

如果设置了该选项,HTTP 服务器将监听 Unix 套接字而不是端口。

¥If set, the HTTP server will listen on a unix socket instead of a port.

(不能与主机名+端口一起使用)

¥(Cannot be used with hostname+port)

serve.tls

我们可以通过传入 key 和 cert 的值来启用 TLS(SSL 的后继者);两者都是启用 TLS 所必需的。

¥We can enable TLS (known as successor of SSL) by passing in a value for key and cert; both are required to enable TLS.

ts
import { Elysia, file } from 'elysia'

new Elysia({
	serve: {
		tls: {
			cert: file('cert.pem'),
			key: file('key.pem')
		}
	}
})

Elysia 扩展了 Bun 配置,该配置支持开箱即用的 TLS,由 BoringSSL 提供支持。

¥Elysia extends Bun configuration which supports TLS out of the box, powered by BoringSSL.

serve.tls.ca

可选地覆盖受信任的 CA 证书。默认信任 Mozilla 授权的知名 CA。

¥Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla.

当使用此选项明确指定 CA 时,Mozilla 的 CA 将被完全替换。

¥Mozilla's CAs are completely replaced when CAs are explicitly specified using this option.

serve.tls.cert

PEM 格式的证书链。每个私钥应提供一个证书链。

¥Cert chains in PEM format. One cert chain should be provided per private key.

每个证书链应按顺序包含所提供私钥的 PEM 格式证书,以及 PEM 格式的中间证书(如果有),且不包括根 CA(对等方必须预先知道根 CA,请参阅 ca)。

¥Each cert chain should consist of the PEM formatted certificate for a provided private key, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see ca).

提供多个证书链时,它们的顺序不必与密钥中的私钥顺序相同。

¥When providing multiple cert chains, they do not have to be in the same order as their private keys in key.

如果未提供中间证书,对等方将无法验证证书,握手将失败。

¥If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.

serve.tls.dhParamsFile

.pem 文件的路径 自定义 Diffie-Helman 参数

¥File path to a .pem file custom Diffie Helman parameters

serve.tls.key

PEM 格式的私钥。PEM 允许加密私钥。加密密钥将使用 options.passphrase 解密。

¥Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with options.passphrase.

使用不同算法的多个密钥可以以未加密的密钥字符串或缓冲区数组的形式提供,也可以以 形式的对象数组的形式提供。

¥Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form .

对象形式只能以数组形式出现。

¥The object form can only occur in an array.

object.passphrase 为可选。加密密钥将使用以下方式解密:

¥object.passphrase is optional. Encrypted keys will be decrypted with

如果提供了 object.passphrase,则使用 object.passphrase;如果没有提供,则使用 options.passphrase。

¥object.passphrase if provided, or options.passphrase if it is not.

serve.tls.lowMemoryMode

@default false

这将 OPENSSL_RELEASE_BUFFERS 设置为 1。

¥This sets OPENSSL_RELEASE_BUFFERS to 1.

它会降低整体性能,但会节省一些内存。

¥It reduces overall performance but saves some memory.

serve.tls.passphrase

单个私钥和/或 PFX 文件的共享密码。

¥Shared passphrase for a single private key and/or a PFX.

serve.tls.requestCert

@default false

如果设置为 true,则服务器将请求客户端证书。

¥If set to true, the server will request a client certificate.

serve.tls.secureOptions

可选地影响 OpenSSL 协议行为,这通常不是必需的。

¥Optionally affect the OpenSSL protocol behavior, which is not usually necessary.

如果要使用,请务必谨慎!

¥This should be used carefully if at all!

值是 OpenSSL 选项中 SSL_OP_* 选项的数字位掩码

¥Value is a numeric bitmask of the SSL_OP_* options from OpenSSL Options

serve.tls.serverName

显式设置服务器名称

¥Explicitly set a server name

tags

为实例的所有路由定义类似于 detail 的 OpenAPI 模式标签

¥Define an tags for OpenAPI schema for all routes of an instance similar to detail

ts
import { 
Elysia
} from 'elysia'
new
Elysia
({
tags
: ['elysia']
})

systemRouter

尽可能使用运行时/框架提供的路由。

¥Use runtime/framework provided router if possible.

在 Bun 上,Elysia 将使用 Bun.serve.routes 并回退到 Elysia 自己的路由。

¥On Bun, Elysia will use Bun.serve.routes and fallback to Elysia's own router.

websocket

覆盖 websocket 配置

¥Override websocket configuration

建议将此设置为默认值,因为 Elysia 会自动生成合适的配置来处理 WebSocket。

¥Recommended to leave this as default as Elysia will generate suitable configuration for handling WebSocket automatically

此配置扩展了 Bun 的 WebSocket API

¥This configuration extends Bun's WebSocket API

示例

¥Example

ts
import { Elysia } from 'elysia'

new Elysia({
	websocket: {
		// enable compression and decompression
    	perMessageDeflate: true
	}
})