Skip to content

Eden 条约

¥Eden Treaty

Eden Treaty 是一个用于与服务器交互的对象表示,具有类型安全、自动补齐和错误处理功能。

¥Eden Treaty is an object representation to interact with a server and features type safety, auto-completion, and error handling.

要使用 Eden Treaty,首先导出你现有的 Elysia 服务器类型:

¥To use Eden Treaty, first export your existing Elysia server type:

typescript
// server.ts
import { Elysia, t } from 'elysia'

const app = new Elysia()
    .get('/hi', () => 'Hi Elysia')
    .get('/id/:id', ({ params: { id } }) => id)
    .post('/mirror', ({ body }) => body, {
        body: t.Object({
            id: t.Number(),
            name: t.String()
        })
    })
    .listen(3000)

export type App = typeof app 

然后导入服务器类型并在客户端使用 Elysia API:

¥Then import the server type and consume the Elysia API on the client:

typescript
// client.ts
import { 
treaty
} from '@elysiajs/eden'
import type {
App
} from './server'
const
app
=
treaty
<
App
>('localhost:3000')
// response type: 'Hi Elysia' const {
data
,
error
} = await
app
.
hi
.
get
()

树状语法

¥Tree like syntax

HTTP 路径是文件系统树的资源指示器。

¥HTTP Path is a resource indicator for a file system tree.

文件系统由多层级文件夹组成,例如:

¥File system consists of multiple levels of folders, for example:

  • /documents/elysia

  • /documents/kalpas

  • /documents/kelvin

每个级别由 /(斜杠)和名称分隔。

¥Each level is separated by / (slash) and a name.

然而,在 JavaScript 中,我们使用 "."(点)而不是 "/"(斜杠)来访问更深层的资源。

¥However in JavaScript, instead of using "/" (slash) we use "." (dot) to access deeper resources.

Eden Treaty 将 Elysia 服务器转换为树状文件系统,以便 JavaScript 前端进行访问。

¥Eden Treaty turns an Elysia server into a tree-like file system that can be accessed in the JavaScript frontend instead.

路径条约
/
/hi.hi
/deep/nested.deep.nested

结合 HTTP 方法,我们可以与 Elysia 服务器交互。

¥Combined with the HTTP method, we can interact with the Elysia server.

路径方法条约
/GET.get()
/hiGET.hi.get()
/deep/nestedGET.deep.nested.get()
/deep/nestedPOST.deep.nested.post()

动态路径

¥Dynamic path

但是,动态路径参数无法使用符号表示。如果完全替换它们,我们就不知道参数名称应该是什么了。

¥However, dynamic path parameters cannot be expressed using notation. If they are fully replaced, we don't know what the parameter name is supposed to be.

typescript
// ❌ Unclear what the value is supposed to represent?
treaty.item['skadi'].get()

为了处理这种情况,我们可以使用函数指定动态路径来提供键值。

¥To handle this, we can specify a dynamic path using a function to provide a key value instead.

typescript
// ✅ Clear that value is dynamic path is 'name'
treaty.item({ name: 'Skadi' }).get()
路径条约
/item.item
/item/:name.item({ name: 'Skadi' })
/item/:name/id.item({ name: 'Skadi' }).id