Skip to content

与 Astro 集成

¥Integration with Astro

通过 Astro 端点,我们可以直接在 Astro 上运行 Elysia。

¥With Astro Endpoint, we can run Elysia on Astro directly.

  1. 在 astro.config.mjs 中将输出设置为服务器
javascript
// astro.config.mjs
import { defineConfig } from 'astro/config'

// https://astro.build/config
export default defineConfig({
    output: 'server'
})
  1. 创建 pages/[...slugs].ts
  2. 在 [...slugs].ts 中创建或导入现有的 Elysia 服务器
  3. 使用你想要公开的方法名称导出处理程序
typescript
// pages/[...slugs].ts
import { Elysia, t } from 'elysia'

const app = new Elysia()
    .get('/api', () => 'hi')
    .post('/api', ({ body }) => body, {
        body: t.Object({
            name: t.String()
        })
    })

const handle = ({ request }: { request: Request }) => app.handle(request) 

export const GET = handle 
export const POST = handle 

由于符合 WinterCG 标准,Elysia 将按预期正常工作。

¥Elysia will work normally as expected because of WinterCG compliance.

我们建议运行 Astro 开启 Bun,因为 Elysia 旨在在 Bun 上运行。

¥We recommend running Astro on Bun as Elysia is designed to be run on Bun.

提示

由于 WinterCG 支持,你可以在 Bun 上运行 Elysia 服务器而无需运行 Astro。

¥You can run Elysia server without running Astro on Bun thanks to WinterCG support.

然而,如果你在 Node 上运行 Astro,某些插件(如 Elysia Static)可能无法工作。

¥However, some plugins like Elysia Static may not work if you are running Astro on Node.

通过这种方法,你可以将前端和后端共存于一个存储库中,并通过 Eden 实现端到端的类型安全。

¥With this approach, you can have co-location of both frontend and backend in a single repository and have End-to-end type-safety with Eden.

更多信息请参阅 Astro 端点

¥Please refer to Astro Endpoint for more information.

前缀

¥Prefix

如果你将 Elysia 服务器放置在应用路由的根目录之外,则需要将前缀注释为 Elysia 服务器。

¥If you place an Elysia server not in the root directory of the app router, you need to annotate the prefix to the Elysia server.

例如,如果你将 Elysia 服务器放置在 pages/api/[...slugs].ts 中,则需要将 Elysia 服务器的前缀注释为 /api。

¥For example, if you place Elysia server in pages/api/[...slugs].ts, you need to annotate prefix as /api to Elysia server.

typescript
// pages/api/[...slugs].ts
import { Elysia, t } from 'elysia'

const app = new Elysia({ prefix: '/api' }) 
    .get('/', () => 'hi')
    .post('/', ({ body }) => body, {
        body: t.Object({
            name: t.String()
        })
    })

const handle = ({ request }: { request: Request }) => app.handle(request) 

export const GET = handle 
export const POST = handle 

这将确保 Elysia 路由在你放置它的任何位置都能正常工作。

¥This will ensure that Elysia routing will work properly in any location you place it.