Files
d8d-vite-starter/src/server/index.tsx
D8D Developer b9a3c991d0 update
2025-06-27 01:56:30 +00:00

75 lines
2.1 KiB
TypeScript

import 'dotenv/config'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { swaggerUI } from '@hono/swagger-ui'
import * as fs from 'fs/promises'
import { renderer } from './renderer'
import createApi from './api'
const app = new Hono();
// Middleware chain
app.use('*', logger())
app.use('*', cors(
// {
// origin: ['http://localhost:3000'],
// allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
// credentials: true
// }
))
app.route('/', createApi)
if(!import.meta.env.PROD){
app.get('/ui', swaggerUI({
url: '/doc',
persistAuthorization: true
}))
}
if(import.meta.env.PROD){
app.get('/assets/:filename', async (c) => {
const filename = c.req.param('filename')
const filePath = import.meta.env.PROD? `./dist/assets/${filename}` : `./public/assets/${filename}`
const content = await fs.readFile(filePath);
const modifyDate = (await fs.stat(filePath))?.mtime?.toUTCString()?? new Date().toUTCString();
const fileExt = filePath.split('.').pop()?.toLowerCase()
// 根据文件扩展名设置适当的 Content-Type
if (fileExt === 'tsx' || fileExt === 'ts') {
c.header('Content-Type', 'text/typescript; charset=utf-8')
} else if (fileExt === 'js' || fileExt === 'mjs') {
c.header('Content-Type', 'application/javascript; charset=utf-8')
} else if (fileExt === 'json') {
c.header('Content-Type', 'application/json; charset=utf-8')
} else if (fileExt === 'html') {
c.header('Content-Type', 'text/html; charset=utf-8')
} else if (fileExt === 'css') {
c.header('Content-Type', 'text/css; charset=utf-8')
} else if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExt || '')) {
c.header('Content-Type', `image/${fileExt}`)
}
return c.body(content, {
headers: {
// 'Content-Type': 'text/html; charset=utf-8',
'Last-Modified': modifyDate
}
})
})
}
app.use(renderer)
app.get('/*', (c) => {
return c.render(
<>
<div id="root"></div>
</>
)
})
export default app