Skip to content

响应

¥Response

调用 fetch 方法后,Eden Treaty 将返回一个包含以下属性的对象 Promise

¥Once the fetch method is called, Eden Treaty returns a Promise containing an object with the following properties:

  • data - 响应的返回值 (2xx)

  • error - 响应的返回值 (>= 3xx)

  • 响应 Response - Web 标准响应类

  • 状态 number - HTTP 状态码

  • 标头 FetchRequestInit['headers'] - 响应头

返回后,必须提供错误处理机制,以确保响应数据值已解包,否则该值将为可空值。Elysia 提供 error() 辅助函数来处理错误,Eden 将提供错误值的类型缩减功能。

¥Once returned, you must provide error handling to ensure that the response data value is unwrapped, otherwise the value will be nullable. Elysia provides a error() helper function to handle the error, and Eden will provide type narrowing for the error value.

typescript
import { Elysia, t } from 'elysia'
import { treaty } from '@elysiajs/eden'

const app = new Elysia()
    .post('/user', ({ body: { name }, status }) => {
        if(name === 'Otto') return status(400)

        return name
    }, {
        body: t.Object({
            name: t.String()
        })
    })
    .listen(3000)

const api = treaty<typeof app>('localhost:3000')

const submit = async (name: string) => {
    const { data, error } = await api.user.post({
        name
    })

    // type: string | null
    console.log(data)

    if (error)
        switch(error.status) {
            case 400:
                // Error type will be narrow down
                throw error.value

            default:
                throw error.value
        }

    // Once the error is handled, type will be unwrapped
    // type: string
    return data
}

默认情况下,Elysia 会自动将 errorresponse 类型推断为 TypeScript,并且 Eden 将提供自动补齐和类型缩小功能以确保准确的行为。

¥By default, Elysia infers error and response types to TypeScript automatically, and Eden will be providing auto-completion and type narrowing for accurate behavior.

提示

如果服务器响应的 HTTP 状态码 >= 300,则该值将始终为 null,而返回值将改为 error

¥If the server responds with an HTTP status >= 300, then the value will always be null, and error will have a returned value instead.

否则,响应将传递给 data

¥Otherwise, response will be passed to data.

Stream 响应

¥Stream response

Eden 会将流响应或 服务器发送事件 解释为 AsyncGenerator,从而允许我们使用 for await 循环来使用该流。

¥Eden will interpret a stream response or Server-Sent Events as AsyncGenerator allowing us to use for await loop to consume the stream.

typescript
import { 
Elysia
} from 'elysia'
import {
treaty
} from '@elysiajs/eden'
const
app
= new
Elysia
()
.
get
('/ok', function* () {
yield 1 yield 2 yield 3 }) const {
data
,
error
} = await
treaty
(
app
).
ok
.
get
()
if (
error
) throw
error
for await (const
chunk
of
data
)
console
.
log
(
chunk
)
typescript
import { 
Elysia
,
sse
} from 'elysia'
import {
treaty
} from '@elysiajs/eden'
const
app
= new
Elysia
()
.
get
('/ok', function* () {
yield
sse
({
event
: 'message',
data
: 1
}) yield
sse
({
event
: 'message',
data
: 2
}) yield
sse
({
event
: 'end'
}) }) const {
data
,
error
} = await
treaty
(
app
).
ok
.
get
()
if (
error
) throw
error
for await (const
chunk
of
data
)
console
.
log
(
chunk
)
//

工具类型

¥Utility type

Eden Treaty 提供了实用类型 Treaty.Data<T>Treaty.Error<T>,用于从响应中提取 dataerror 类型。

¥Eden Treaty provides a utility type Treaty.Data<T> and Treaty.Error<T> to extract the data and error type from the response.

typescript
import { 
Elysia
,
t
} from 'elysia'
import {
treaty
, Treaty } from '@elysiajs/eden'
const
app
= new
Elysia
()
.
post
('/user', ({
body
: {
name
},
status
}) => {
if(
name
=== 'Otto') return
status
(400)
return
name
}, {
body
:
t
.
Object
({
name
:
t
.
String
()
}) }) .
listen
(3000)
const
api
=
treaty
<typeof
app
>('localhost:3000')
type
UserData
= Treaty.
Data
<typeof
api
.
user
.
post
>
// Alternatively you can also pass a response const
response
= await
api
.
user
.
post
({
name
: 'Saltyaom'
}) type
UserDataFromResponse
= Treaty.
Data
<typeof
response
>
type
UserError
= Treaty.
Error
<typeof
api
.
user
.
post
>
//