| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- import { OpenAPIHono } from '@hono/zod-openapi'
- import { errorHandler } from './utils/errorHandler'
- import usersRouter from './api/users/index'
- import authRoute from './api/auth/index'
- import { AuthContext } from './types/context'
- import { AppDataSource } from './data-source'
- const api = new OpenAPIHono<AuthContext>()
- api.onError(errorHandler)
- // Rate limiting
- api.use('/api/v1/*', async (c, next) => {
- const ip = c.req.header('x-forwarded-for') || c.req.header('cf-connecting-ip')
- // 实现速率限制逻辑
- await next()
- })
- // 数据库初始化中间件
- api.use('/api/v1/*', async (c, next) => {
- if(!AppDataSource.isInitialized) {
- await AppDataSource.initialize();
- }
- await next();
- })
- // 注册Bearer认证方案
- api.openAPIRegistry.registerComponent('securitySchemes','bearerAuth',{
- type:'http',
- scheme:'bearer',
- bearerFormat:'JWT',
- description:'使用JWT进行认证'
- })
- // OpenAPI documentation endpoint
- if(!import.meta.env.PROD){
- api.doc31('/doc', {
- openapi: '3.1.0',
- info: {
- title: 'API Documentation',
- version: '1.0.0'
- },
- security: [{
- bearerAuth: []
- }]
- // servers: [{ url: '/api/v1' }]
- })
- }
- const userRoutes = api.route('/api/v1/users', usersRouter)
- const authRoutes = api.route('/api/v1/auth', authRoute)
- export type AuthRoutes = typeof authRoutes
- export type UserRoutes = typeof userRoutes
- export default api
|