在 Bun 环境下使用 Elysia 框架,可以通过多种形式设定路由,以满足不同的需求和场景。Elysia 提供了多种路由定义方法,包括基本路由、路由组、嵌套路由等。以下是一些常见的路由设定形式及其实现代码示例。

1. 基本路由

基本路由是最常见和最简单的形式,通过指定 HTTP 方法(如 GET、POST 等)来定义路由处理器。

import { Elysia } from 'elysia';
 
const app = new Elysia();
 
app.get('/hello', (req, res) => {
  res.send('Hello, World!');
});
 
app.post('/data', (req, res) => {
  const data = req.body;
  res.json({ received: data });
});
 
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

2. 路由组

路由组允许你将多个相关路由组织在一起,通常用于给路由添加公共前缀或中间件。

import { Elysia } from 'elysia';
 
const app = new Elysia();
 
const userRouter = new Elysia.Router();
 
userRouter
  .get('/', (req, res) => {
    res.json({ message: 'List of users' });
  })
  .get('/:id', (req, res) => {
    const userId = req.params.id;
    res.json({ message: `User with ID: ${userId}` });
  });
 
app.use('/users', userRouter);
 
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

3. 嵌套路由

嵌套路由允许在路由组中进一步嵌套子路由组,这对于构建复杂的 API 结构非常有用。

import { Elysia } from 'elysia';
 
const app = new Elysia();
 
const postRouter = new Elysia.Router();
 
postRouter
  .get('/', (req, res) => {
    res.json({ message: 'List of posts' });
  })
  .get('/:id', (req, res) => {
    const postId = req.params.id;
    res.json({ message: `Post with ID: ${postId}` });
  });
 
const userRouter = new Elysia.Router();
 
userRouter
  .get('/', (req, res) => {
    res.json({ message: 'List of users' });
  })
  .get('/:id', (req, res) => {
    const userId = req.params.id;
    res.json({ message: `User with ID: ${userId}` });
  })
  .use('/:userId/posts', postRouter);
 
app.use('/users', userRouter);
 
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

4. 动态路由

动态路由允许你在路径中使用参数,这些参数可以在处理器中访问。

import { Elysia } from 'elysia';
 
const app = new Elysia();
 
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  res.json({ message: `User with ID: ${userId}` });
});
 
app.get('/posts/:postId/comments/:commentId', (req, res) => {
  const { postId, commentId } = req.params;
  res.json({ message: `Post ID: ${postId}, Comment ID: ${commentId}` });
});
 
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

5. 使用中间件

中间件可以在路由处理之前对请求进行预处理,通常用于身份验证、日志记录等。

import { Elysia } from 'elysia';
 
const app = new Elysia();
 
const authMiddleware = (req, res, next) => {
  if (req.headers.authorization) {
    next();
  } else {
    res.status(401).send('Unauthorized');
  }
};
 
app.use(authMiddleware);
 
app.get('/protected', (req, res) => {
  res.send('This is a protected route');
});
 
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

总结

以上是使用 Elysia 框架在 Bun 环境下定义路由的几种常见形式。通过基本路由、路由组、嵌套路由、动态路由以及使用中间件,你可以构建一个结构清晰、功能丰富的后端应用程序。Elysia 提供了灵活且易于使用的路由定义方式,使得开发高效且可维护的 TypeScript 应用成为可能。