index.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import 'dotenv/config'
  2. import { Hono } from 'hono'
  3. import { cors } from 'hono/cors'
  4. import { logger } from 'hono/logger'
  5. import { swaggerUI } from '@hono/swagger-ui'
  6. import * as fs from 'fs/promises'
  7. import { renderer } from './renderer'
  8. import createApi from './api'
  9. const app = new Hono();
  10. // Middleware chain
  11. app.use('*', logger())
  12. app.use('*', cors(
  13. // {
  14. // origin: ['http://localhost:3000'],
  15. // allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  16. // credentials: true
  17. // }
  18. ))
  19. app.route('/', createApi)
  20. if(!import.meta.env.PROD){
  21. app.get('/ui', swaggerUI({
  22. url: '/doc',
  23. persistAuthorization: true,
  24. manuallySwaggerUIHtml: (asset) => `
  25. <div>
  26. <div id="swagger-ui"></div>
  27. <link rel="stylesheet" href="https://ai-oss.d8d.fun/swagger-ui-dist/swagger-ui.css" />
  28. <script src="https://ai-oss.d8d.fun/swagger-ui-dist/swagger-ui-bundle.js" crossorigin="anonymous"></script>
  29. <script>
  30. window.onload = () => {
  31. window.ui = SwaggerUIBundle({
  32. dom_id: '#swagger-ui',
  33. url: '/doc',
  34. persistAuthorization: true
  35. })
  36. }
  37. </script>
  38. </div>
  39. `
  40. }))
  41. }
  42. if(import.meta.env.PROD){
  43. app.get('/assets/:filename', async (c) => {
  44. const filename = c.req.param('filename')
  45. const filePath = import.meta.env.PROD? `./dist/assets/${filename}` : `./public/assets/${filename}`
  46. const content = await fs.readFile(filePath);
  47. const modifyDate = (await fs.stat(filePath))?.mtime?.toUTCString()?? new Date().toUTCString();
  48. const fileExt = filePath.split('.').pop()?.toLowerCase()
  49. // 根据文件扩展名设置适当的 Content-Type
  50. if (fileExt === 'tsx' || fileExt === 'ts') {
  51. c.header('Content-Type', 'text/typescript; charset=utf-8')
  52. } else if (fileExt === 'js' || fileExt === 'mjs') {
  53. c.header('Content-Type', 'application/javascript; charset=utf-8')
  54. } else if (fileExt === 'json') {
  55. c.header('Content-Type', 'application/json; charset=utf-8')
  56. } else if (fileExt === 'html') {
  57. c.header('Content-Type', 'text/html; charset=utf-8')
  58. } else if (fileExt === 'css') {
  59. c.header('Content-Type', 'text/css; charset=utf-8')
  60. } else if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExt || '')) {
  61. c.header('Content-Type', `image/${fileExt}`)
  62. }
  63. return c.body(content, {
  64. headers: {
  65. // 'Content-Type': 'text/html; charset=utf-8',
  66. 'Last-Modified': modifyDate
  67. }
  68. })
  69. })
  70. }
  71. app.use(renderer)
  72. app.get('/*', (c) => {
  73. return c.render(
  74. <>
  75. <div id="root"></div>
  76. </>
  77. )
  78. })
  79. export default app