主题
端到端类型安全
¥End-to-End Type Safety
假设你有一套玩具火车。
¥Imagine you have a toy train set.
火车轨道的每一部分都必须与下一部分完美契合,就像拼图碎片一样。
¥Each piece of the train track has to fit perfectly with the next one, like puzzle pieces.
端到端类型安全就像确保轨道的所有部分都正确匹配,这样火车就不会掉下来或卡住。
¥End-to-end type safety is like making sure all the pieces of the track match up correctly so the train doesn't fall off or get stuck.
对于一个框架来说,拥有端到端类型安全意味着你可以以类型安全的方式连接客户端和服务器。
¥For a framework to have end-to-end type safety means you can connect client and server in a type-safe manner.
Elysia 提供了一个类似 RPC 的连接器 Eden,无需生成代码即可提供端到端的类型安全。
¥Elysia provides end-to-end type safety without code generation out of the box with an RPC-like connector, Eden
其他支持端到端类型安全的框架:
¥Other frameworks that support e2e type safety:
tRPC
Remix
SvelteKit
Nuxt
TS-Rest
Elysia 允许你在服务器上更改类型,并且更改会立即反映在客户端,从而有助于自动补齐和类型强制执行。
¥Elysia allows you to change the type on the server and it will be instantly reflected on the client, helping with auto-completion and type-enforcement.
Eden
Eden 是一个类似 RPC 的客户端,它仅使用 TypeScript 的类型推断(而非代码生成)即可实现 Elysia 的端到端类型安全连接。
¥Eden is an RPC-like client to connect Elysia with end-to-end type safety using only TypeScript's type inference instead of code generation.
它允许你轻松同步客户端和服务器类型,大小不到 2KB。
¥It allows you to sync client and server types effortlessly, weighing less than 2KB.
Eden 包含两个模块:
¥Eden consists of 2 modules:
- Eden 条约(推荐):一个改进版的 Eden Treaty RFC 版本
- Eden 获取:具有类型安全性的类似 Fetch 的客户端
以下是每个模块的概述、用例和比较。
¥Below is an overview, use-case and comparison for each module.
Eden 条约(推荐)
¥Eden Treaty (Recommended)
Eden Treaty 是一个 Elysia 服务器的对象表示,提供端到端的类型安全,并显著提升开发者体验。
¥Eden Treaty is an object-like representation of an Elysia server providing end-to-end type safety and a significantly improved developer experience.
借助 Eden Treaty,我们可以与具有完整类型支持和自动补齐功能的 Elysia 服务器交互,使用类型收缩进行错误处理,并创建类型安全的单元测试。
¥With Eden Treaty we can interact with an Elysia server with full-type support and auto-completion, error handling with type narrowing, and create type-safe unit tests.
Eden 条约 (Eden Treaty) 用法示例:
¥Example usage of Eden Treaty:
typescript
import { treaty } from '@elysiajs/eden'
import type { App } from './server'
const app = treaty<App>('localhost:3000')
app.
// Call [GET] at '/'
const { data } = await app.get()
// Call [PUT] at '/nendoroid/:id'
const { data: nendoroid, error } = await app.nendoroid({ id: 1895 }).put({
name: 'Skadi',
from: 'Arknights'
})
Eden 获取
¥Eden Fetch
对于喜欢使用 Fetch 语法的开发者来说,这是一个类似于 Eden Treaty 的替代方案。
¥A fetch-like alternative to Eden Treaty for developers that prefers fetch syntax.
typescript
import { edenFetch } from '@elysiajs/eden'
import type { App } from './server'
const fetch = edenFetch<App>('http://localhost:3000')
const { data } = await fetch('/name/:name', {
method: 'POST',
params: {
name: 'Saori'
},
body: {
branch: 'Arius',
type: 'Striker'
}
})
注意
与 Eden Treaty 不同,Eden Fetch 不为 Elysia 服务器提供 Web Socket 实现。
¥Unlike Eden Treaty, Eden Fetch doesn't provide Web Socket implementation for Elysia server.