Skip to content

与 SvelteKit 集成

¥Integration with SvelteKit

使用 SvelteKit,你可以在服务器路由上运行 Elysia。

¥With SvelteKit, you can run Elysia on server routes.

  1. 创建 src/routes/[...slugs]/+server.ts。
  2. 在 +server.ts 中,创建或导入一个现有的 Elysia 服务器
  3. 使用你想要公开的方法名称导出处理程序。你还可以使用 fallback 让 Elysia 处理所有方法。
typescript
// src/routes/[...slugs]/+server.ts
import { Elysia, t } from 'elysia';

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

type RequestHandler = (v: { request: Request }) => Response | Promise<Response>

export const GET: RequestHandler = ({ request }) => app.handle(request)
export const POST: RequestHandler = ({ request }) => app.handle(request)
// or simply
export const fallback: RequestHandler = ({ request }) => app.handle(request)

你可以将 Elysia 服务器视为普通的 SvelteKit 服务器路由。

¥You can treat the Elysia server as a normal SvelteKit server route.

通过这种方法,你可以将前端和后端共存于一个存储库中,并且 使用 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 with both client-side and server action

更多信息请参阅 SvelteKit 路由

¥Please refer to SvelteKit Routing 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 服务器放置在 src/routes/api/[...slugs]/+server.ts 中,则需要将 Elysia 服务器的前缀注释为 /api。

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

typescript
// src/routes/api/[...slugs]/+server.ts
import { 
Elysia
,
t
} from 'elysia';
const
app
= new
Elysia
({
prefix
: '/api' })
.
get
('/', () => 'hi')
.
post
('/', ({
body
}) =>
body
, {
body
:
t
.
Object
({
name
:
t
.
String
()
}) }) type
RequestHandler
= (
v
: {
request
: Request }) => Response |
Promise
<Response>
export const
fallback
:
RequestHandler
= ({
request
}) =>
app
.
handle
(
request
)

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

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