参数
我们最终需要向服务器发送一个负载。
为此,Eden Treaty 的方法接受 2 个参数来向服务器发送数据。
两个参数都是类型安全的,并且会由 TypeScript 自动引导:
- body
- 其他参数
- query
- headers
- fetch
typescript
import { Elysia, t } from 'elysia'
import { treaty } from '@elysia/eden'
const app = new Elysia()
.post('/user', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
.listen(3000)
const api = treaty<typeof app>('localhost:3000')
// ✅ 有效
api.user.post({
name: 'Elysia'
})
// ✅ 也有效
api.user.post({
name: 'Elysia'
}, {
// 未在模式中指定,这是可选的
headers: {
authorization: 'Bearer 12345'
},
query: {
id: 2
}
})除非该方法不接受 body,那么 body 会被省略,仅有一个参数。
如果方法是 "GET" 或 "HEAD":
- 其他参数
- query
- headers
- fetch
typescript
import { Elysia } from 'elysia'
import { treaty } from '@elysia/eden'
const app = new Elysia()
.get('/hello', () => 'hi')
.listen(3000)
const api = treaty<typeof app>('localhost:3000')
// ✅ 有效
api.hello.get({
// 未在模式中指定,这是可选的
headers: {
hello: 'world'
}
})空 body
如果 body 是可选的或不需要,但 query 或 headers 是必需的,则可以将 body 传递为 null 或 undefined。
typescript
import { Elysia, t } from 'elysia'
import { treaty } from '@elysia/eden'
const app = new Elysia()
.post('/user', () => 'hi', {
query: t.Object({
name: t.String()
})
})
.listen(3000)
const api = treaty<typeof app>('localhost:3000')
api.user.post(null, {
query: {
name: 'Ely'
}
})Fetch 参数
Eden Treaty 是 fetch 的包装器;我们可以通过传递参数给 $fetch 来添加任何有效的 Fetch 参数:
typescript
import { Elysia, t } from 'elysia'
import { treaty } from '@elysia/eden'
const app = new Elysia()
.get('/hello', () => 'hi')
.listen(3000)
const api = treaty<typeof app>('localhost:3000')
const controller = new AbortController()
const cancelRequest = setTimeout(() => {
controller.abort()
}, 5000)
await api.hello.get({
fetch: {
signal: controller.signal
}
})
clearTimeout(cancelRequest)文件上传
我们可以传递以下任意一种来附加文件:
- File
- File[]
- FileList
- Blob
附加文件时,content-type 将为 multipart/form-data
假设我们的服务器如下:
typescript
import { Elysia, t } from 'elysia'
import { treaty } from '@elysia/eden'
const app = new Elysia()
.post('/image', ({ body: { image, title } }) => title, {
body: t.Object({
title: t.String(),
image: t.Files()
})
})
.listen(3000)
export const api = treaty<typeof app>('localhost:3000')
const images = document.getElementById('images') as HTMLInputElement
const { data } = await api.image.post({
title: "Misono Mika",
image: images.files!,
})