Skip to content

备忘单

¥Cheat Sheet

以下是 Elysia 常见模式的快速概述

¥Here are a quick overview for a common Elysia patterns

你好,世界

¥Hello World

一个简单的 Hello World

¥A simple hello world

typescript
import { Elysia } from 'elysia'

new Elysia()
    .get('/', () => 'Hello World')
    .listen(3000)

自定义 HTTP 方法

¥Custom HTTP Method

使用自定义 HTTP 方法/动词定义路由

¥Define route using custom HTTP methods/verbs

参见 路由

¥See Route

typescript
import { Elysia } from 'elysia'

new Elysia()
    .get('/hi', () => 'Hi')
    .post('/hi', () => 'From Post')
    .put('/hi', () => 'From Put')
    .route('M-SEARCH', '/hi', () => 'Custom Method')
    .listen(3000)

路径参数

¥Path Parameter

使用动态路径参数

¥Using dynamic path parameter

参见 路径

¥See Path

typescript
import { Elysia } from 'elysia'

new Elysia()
    .get('/id/:id', ({ params: { id } }) => id)
    .get('/rest/*', () => 'Rest')
    .listen(3000)

返回 JSON

¥Return JSON

Elysia 自动将响应转换为 JSON

¥Elysia converts response to JSON automatically

参见 处理程序

¥See Handler

typescript
import { Elysia } from 'elysia'

new Elysia()
    .get('/json', () => {
        return {
            hello: 'Elysia'
        }
    })
    .listen(3000)

返回文件

¥Return a file

文件可以作为表单数据响应返回。

¥A file can be return in as formdata response

响应必须是 1 级深度对象

¥The response must be a 1-level deep object

typescript
import { Elysia, file } from 'elysia'

new Elysia()
    .get('/json', () => {
        return {
            hello: 'Elysia',
            image: file('public/cat.jpg')
        }
    })
    .listen(3000)

标头和状态

¥Header and status

设置自定义标头和状态码

¥Set a custom header and a status code

参见 处理程序

¥See Handler

typescript
import { Elysia } from 'elysia'

new Elysia()
    .get('/', ({ set, status }) => {
        set.headers['x-powered-by'] = 'Elysia'

        return status(418, "I'm a teapot")
    })
    .listen(3000)

¥Group

为子路由定义一次前缀

¥Define a prefix once for sub routes

参见

¥See Group

typescript
import { Elysia } from 'elysia'

new Elysia()
    .get("/", () => "Hi")
    .group("/auth", app => {
        return app
            .get("/", () => "Hi")
            .post("/sign-in", ({ body }) => body)
            .put("/sign-up", ({ body }) => body)
    })
    .listen(3000)

Schema

强制路由的数据类型

¥Enforce a data type of a route

参见 验证

¥See Validation

typescript
import { Elysia, t } from 'elysia'

new Elysia()
    .post('/mirror', ({ body: { username } }) => username, {
        body: t.Object({
            username: t.String(),
            password: t.String()
        })
    })
    .listen(3000)

文件上传

¥File upload

参见 Validation#file

¥See Validation#file

typescript
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
()
.
post
('/body', ({
body
}) =>
body
, {
body
:
t
.
Object
({
file
:
t
.
File
({
format
: 'image/*' }),
multipleFiles
:
t
.
Files
()
}) }) .
listen
(3000)

生命周期钩子

¥Lifecycle Hook

按顺序拦截 Elysia 事件

¥Intercept an Elysia event in order

参见 生命周期

¥See Lifecycle

typescript
import { Elysia, t } from 'elysia'

new Elysia()
    .onRequest(() => {
        console.log('On request')
    })
    .on('beforeHandle', () => {
        console.log('Before handle')
    })
    .post('/mirror', ({ body }) => body, {
        body: t.Object({
            username: t.String(),
            password: t.String()
        }),
        afterHandle: () => {
            console.log("After handle")
        }
    })
    .listen(3000)

守护

¥Guard

强制子路由的数据类型

¥Enforce a data type of sub routes

参见 范围

¥See Scope

typescript
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
()
.
guard
({
response
:
t
.
String
()
}, (
app
) =>
app
.
get
('/', () => 'Hi')
// Invalid: will throws error, and TypeScript will report error .
get
('/invalid', () => 1)
Argument of type '() => number' is not assignable to parameter of type 'InlineHandler<NoInfer<IntersectIfObjectSchema<{ body: unknown; headers: unknown; query: unknown; params: {}; cookie: unknown; response: { 200: string; }; }, UnwrapRoute<{ response: TString; }, {}, ""> & {}>>, { ...; } & { ...; }, {}>'. Type '() => number' is not assignable to type '(context: { body: unknown; query: Record<string, string>; params: {}; headers: Record<string, string | undefined>; cookie: Record<string, Cookie<unknown>>; server: Server | null; ... 6 more ...; status: <const Code extends 200 | "OK", T extends Code extends 200 ? { ...; }[Code] : Code extends "Continue" | ... 59 mor...'. Type 'number' is not assignable to type 'Response | MaybePromise<string | ElysiaCustomStatusResponse<200, string, 200>>'.
) .
listen
(3000)

自定义上下文

¥Custom context

为路由上下文添加自定义变量

¥Add custom variable to route context

参见 上下文

¥See Context

typescript
import { Elysia } from 'elysia'

new Elysia()
    .state('version', 1)
    .decorate('getDate', () => Date.now())
    .get('/version', ({
        getDate,
        store: { version }
    }) => `${version} ${getDate()}`)
    .listen(3000)

重定向

¥Redirect

重定向响应

¥Redirect a response

参见 处理程序

¥See Handler

typescript
import { Elysia } from 'elysia'

new Elysia()
    .get('/', () => 'hi')
    .get('/redirect', ({ redirect }) => {
        return redirect('/')
    })
    .listen(3000)

插件

¥Plugin

创建一个单独的实例

¥Create a separate instance

参见 插件

¥See Plugin

typescript
import { Elysia } from 'elysia'

const plugin = new Elysia()
    .state('plugin-version', 1)
    .get('/hi', () => 'hi')

new Elysia()
    .use(plugin)
    .get('/version', ({ store }) => store['plugin-version'])
    .listen(3000)

Web Socket

使用 Web Socket 创建实时连接

¥Create a realtime connection using Web Socket

参见 Web Socket

¥See Web Socket

typescript
import { Elysia } from 'elysia'

new Elysia()
    .ws('/ping', {
        message(ws, message) {
            ws.send('hello ' + message)
        }
    })
    .listen(3000)

OpenAPI 文档

¥OpenAPI documentation

使用 Scalar(或可选)创建交互式文档 Swagger)

¥Create interactive documentation using Scalar (or optionally Swagger)

参见 openapi

¥See openapi

typescript
import { Elysia } from 'elysia'
import { openapi } from '@elysiajs/openapi'

const app = new Elysia()
    .use(openapi())
    .listen(3000)

console.log(`View documentation at "${app.server!.url}openapi" in your browser`);

单元测试

¥Unit Test

编写 Elysia 应用的单元测试

¥Write a unit test of your Elysia app

参见 单元测试

¥See Unit Test

typescript
// test/index.test.ts
import { describe, expect, it } from 'bun:test'
import { Elysia } from 'elysia'

describe('Elysia', () => {
    it('return a response', async () => {
        const app = new Elysia().get('/', () => 'hi')

        const response = await app
            .handle(new Request('http://localhost/'))
            .then((res) => res.text())

        expect(response).toBe('hi')
    })
})

自定义 body 解析器

¥Custom body parser

创建用于解析正文的自定义逻辑

¥Create custom logic for parsing body

参见 解析

¥See Parse

typescript
import { Elysia } from 'elysia'

new Elysia()
    .onParse(({ request, contentType }) => {
        if (contentType === 'application/custom-type')
            return request.text()
    })

GraphQL

使用 GraphQL Yoga 或 Apollo 创建自定义 GraphQL 服务器

¥Create a custom GraphQL server using GraphQL Yoga or Apollo

参见 GraphQL Yoga

¥See GraphQL Yoga

typescript
import { Elysia } from 'elysia'
import { yoga } from '@elysiajs/graphql-yoga'

const app = new Elysia()
    .use(
        yoga({
            typeDefs: /* GraphQL */`
                type Query {
                    hi: String
                }
            `,
            resolvers: {
                Query: {
                    hi: () => 'Hello from Elysia'
                }
            }
        })
    )
    .listen(3000)