index.tsx 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. }))
  25. }
  26. if(import.meta.env.PROD){
  27. app.get('/assets/:filename', async (c) => {
  28. const filename = c.req.param('filename')
  29. const filePath = import.meta.env.PROD? `./dist/assets/${filename}` : `./public/assets/${filename}`
  30. const content = await fs.readFile(filePath);
  31. const modifyDate = (await fs.stat(filePath))?.mtime?.toUTCString()?? new Date().toUTCString();
  32. const fileExt = filePath.split('.').pop()?.toLowerCase()
  33. // 根据文件扩展名设置适当的 Content-Type
  34. if (fileExt === 'tsx' || fileExt === 'ts') {
  35. c.header('Content-Type', 'text/typescript; charset=utf-8')
  36. } else if (fileExt === 'js' || fileExt === 'mjs') {
  37. c.header('Content-Type', 'application/javascript; charset=utf-8')
  38. } else if (fileExt === 'json') {
  39. c.header('Content-Type', 'application/json; charset=utf-8')
  40. } else if (fileExt === 'html') {
  41. c.header('Content-Type', 'text/html; charset=utf-8')
  42. } else if (fileExt === 'css') {
  43. c.header('Content-Type', 'text/css; charset=utf-8')
  44. } else if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExt || '')) {
  45. c.header('Content-Type', `image/${fileExt}`)
  46. }
  47. return c.body(content, {
  48. headers: {
  49. // 'Content-Type': 'text/html; charset=utf-8',
  50. 'Last-Modified': modifyDate
  51. }
  52. })
  53. })
  54. }
  55. app.use(renderer)
  56. app.get('/*', (c) => {
  57. return c.render(
  58. <>
  59. <div id="root"></div>
  60. </>
  61. )
  62. })
  63. export default app