api.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { OpenAPIHono } from '@hono/zod-openapi'
  2. import { errorHandler } from './utils/errorHandler'
  3. import usersRouter from './api/users/index'
  4. import authRoute from './api/auth/index'
  5. import { AuthContext } from './types/context'
  6. import { AppDataSource } from './data-source'
  7. const api = new OpenAPIHono<AuthContext>()
  8. api.onError(errorHandler)
  9. // Rate limiting
  10. api.use('/api/v1/*', async (c, next) => {
  11. const ip = c.req.header('x-forwarded-for') || c.req.header('cf-connecting-ip')
  12. // 实现速率限制逻辑
  13. await next()
  14. })
  15. // 数据库初始化中间件
  16. api.use('/api/v1/*', async (c, next) => {
  17. if(!AppDataSource.isInitialized) {
  18. await AppDataSource.initialize();
  19. }
  20. await next();
  21. })
  22. // 注册Bearer认证方案
  23. api.openAPIRegistry.registerComponent('securitySchemes','bearerAuth',{
  24. type:'http',
  25. scheme:'bearer',
  26. bearerFormat:'JWT',
  27. description:'使用JWT进行认证'
  28. })
  29. // OpenAPI documentation endpoint
  30. if(!import.meta.env.PROD){
  31. api.doc31('/doc', {
  32. openapi: '3.1.0',
  33. info: {
  34. title: 'API Documentation',
  35. version: '1.0.0'
  36. },
  37. security: [{
  38. bearerAuth: []
  39. }]
  40. // servers: [{ url: '/api/v1' }]
  41. })
  42. }
  43. const userRoutes = api.route('/api/v1/users', usersRouter)
  44. const authRoutes = api.route('/api/v1/auth', authRoute)
  45. export type AuthRoutes = typeof authRoutes
  46. export type UserRoutes = typeof userRoutes
  47. export default api