-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhono-server.ts
More file actions
89 lines (76 loc) · 2.06 KB
/
hono-server.ts
File metadata and controls
89 lines (76 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { type HttpBindings, serve } from '@hono/node-server'
import { serveStatic } from '@hono/node-server/serve-static'
import { Hono } from 'hono'
import { compress } from 'hono/compress'
import { createMiddleware } from 'hono/factory'
import type { ViteDevServer } from 'vite'
const DEVELOPMENT = process.env.NODE_ENV === 'development'
const PORT = Number.parseInt(process.env.PORT || '3000')
const app = new Hono<{ Bindings: HttpBindings }>()
const withMiddlewares = (server: ViteDevServer) =>
createMiddleware<{ Bindings: HttpBindings }>(async (c, next) => {
return new Promise((resolve) => {
server.middlewares(c.env.incoming, c.env.outgoing, () => {
resolve(next())
})
})
})
const withDevRequest = (server: ViteDevServer) =>
createMiddleware<{ Bindings: HttpBindings }>(async (c) => {
try {
const { default: serverEntry } =
await server.ssrLoadModule('./src/server.ts')
return await serverEntry.fetch(c.req.raw)
} catch (error) {
if (typeof error === 'object' && error instanceof Error) {
server.ssrFixStacktrace(error)
}
throw error
}
})
const withProdRequest = createMiddleware<{ Bindings: HttpBindings }>(
async (c) => {
const { default: handler } = await import('./dist/server/server.js')
return await handler.fetch(c.req.raw)
},
)
if (DEVELOPMENT) {
const vite = await import('vite')
const server = await vite.createServer({
server: { middlewareMode: true },
appType: 'custom',
})
app.use(withMiddlewares(server))
app.use(withDevRequest(server))
} else {
app.use(compress())
app.use(
'*',
serveStatic({
root: './dist/client',
}),
)
app.use(withProdRequest)
}
const server = serve(
{
fetch: app.fetch,
port: PORT,
},
(info) => {
console.log(`Server is running on http://localhost:${info.port}`)
},
)
process.on('SIGINT', () => {
server.close()
process.exit(0)
})
process.on('SIGTERM', () => {
server.close((err) => {
if (err) {
console.error(err)
process.exit(1)
}
process.exit(0)
})
})