Interactive Playground
当前部署环境只有 2C4G。为了避免构建阶段因 Monaco、Rollup Browser 和 类型分析导致 OOM,这个版本只保留教程内容,不内嵌在线 Playground。
bun run build:full如需完整交互体验,请在更高配置环境执行上面的完整构建命令。
可重用的路由选项。
想象一下我们有一个这样的认证检查:
import { Elysia, t } from 'elysia'
new Elysia()
.post('/user', ({ body }) => body, {
cookie: t.Object({
session: t.String()
}),
beforeHandle({ cookie: { session } }) {
if(!session.value) throw '未授权'
}
})
.listen(3000)如果我们有多个路由需要认证,就必须重复相同的选项。
相反,我们可以使用宏来重用路由选项:
import { Elysia, t } from 'elysia'
new Elysia()
.macro('auth', {
cookie: t.Object({
session: t.String()
}),
// 伪认证检查
beforeHandle({ cookie: { session }, status }) {
if(!session.value) return status(401)
}
})
.post('/user', ({ body }) => body, {
auth: true
})
.listen(3000)auth 将内联 cookie 和 beforeHandle 到路由中。
简单来说,宏 是一个可重用的路由选项,类似函数,但作为带有类型安全的路由选项。
让我们定义一个宏来检查一个数是否是斐波那契数列中的数字:
function isFibonacci(n: number) {
let a = 0, b = 1
while(b < n) [a, b] = [b, a + b]
return b === n || n === 0
}body 属性。status 函数提前返回。import { Elysia, t } from 'elysia'
function isPerfectSquare(x: number) {
const s = Math.floor(Math.sqrt(x))
return s * s === x
}
function isFibonacci(n: number) {
if (n < 0) return false
return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4)
}
new Elysia()
.macro('isFibonacci', {
body: t.Number(),
beforeHandle({ body, status }) {
if(!isFibonacci(body)) return status(418)
}
})
.post('/', ({ body }) => body, {
isFibonacci: true
})
.listen(3000)