返回

Elysia Js Note

目录

路由

常用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { Elysia } from 'elysia'

new Elysia()
    .all('/', 'hi')
    .listen(3000)


import { Elysia } from 'elysia'

const app = new Elysia()
    .get('/get', 'hello')
    .post('/post', 'hi')
    .route('M-SEARCH', '/m-search', 'connect') 
    .listen(3000)

分组路由

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import { Elysia } from 'elysia'

new Elysia()
    .group('/user', (app) =>
        app
            .post('/sign-in', 'Sign in')
            .post('/sign-up', 'Sign up')
            .post('/profile', 'Profile')
    )
    .listen(3000)

前缀

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { Elysia } from 'elysia'

const users = new Elysia({ prefix: '/user' })
    .post('/sign-in', 'Sign in')
    .post('/sign-up', 'Sign up')
    .post('/profile', 'Profile')

new Elysia()
    .use(users)
    .get('/', 'hello world')
    .listen(3000)

生命周期

Interger with OpenAPI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export const sensorRoutes = new Elysia({ prefix: '/v1/sensors' })
    .use(mqttPlugin)
    .guard({
        headers: t.Object({
            authorization: t.String({ error: '需要 API Key' })
        }),
        detail: { tags: ['Sensors'] }
    }, (app) => app
        .onBeforeHandle(({ headers }) => {
            if (!headers.authorization.startsWith('iiot_')) {
                throw new Error('Unauthorized Device');
            }
        })
        .post('/publish', ({ body, mqtt }) => {
            const topic = `sensors/${body.deviceId}/data`;
            mqtt.publish(topic, JSON.stringify(body.payload));
            return { status: 'published', topic };
        }, {
            body: t.Object({
                deviceId: t.String(),
                payload: t.Object({
                    temp: t.Number(),
                    humidity: t.Number()
                })
            }),
            response: t.Object({
                status: t.String(),
                topic: t.String()
            }),

            // 这里
            detail: { summary: '推送传感器数据到 MQTT 总线' }
        })
    );

summary
summary: '上传传感器数据(显示在标题)'

description
description: '该接口用于将设备采集的温湿度通过 MQTT 转发...'

tags
tags: ['设备管理', '传感器数据']

security
security: [{ BearerAuth: [] }]
Licensed under CC BY-NC-SA 4.0