|
1 | 1 | import { Hono } from 'hono'; |
| 2 | +import { parseConfig, type Config } from '../config'; |
2 | 3 | import { pingDatabase } from '../db/ping'; |
3 | 4 |
|
4 | 5 | const startTime = Date.now(); |
5 | 6 |
|
6 | 7 | type Bindings = { |
7 | | - HYPERDRIVE: Hyperdrive; |
| 8 | + HYPERDRIVE: Hyperdrive | undefined; |
8 | 9 | APP_VERSION: string; |
9 | 10 | HEALTH_DB_TIMEOUT_MS: string; |
10 | 11 | }; |
11 | 12 |
|
12 | | -export const healthRoutes = new Hono<{ Bindings: Bindings }>().get('/', async (c) => { |
13 | | - const timeoutMs = Number(c.env.HEALTH_DB_TIMEOUT_MS) || 2000; |
14 | | - const timeout = new Promise<'disconnected'>((resolve) => |
15 | | - setTimeout(() => resolve('disconnected'), timeoutMs), |
16 | | - ); |
| 13 | +type Variables = { |
| 14 | + config: Config; |
| 15 | +}; |
| 16 | + |
| 17 | +export const healthRoutes = new Hono<{ Bindings: Bindings; Variables: Variables }>().get( |
| 18 | + '/', |
| 19 | + async (c) => { |
| 20 | + const config = c.var.config ?? parseConfig(c.env); |
| 21 | + |
| 22 | + const timeout = new Promise<'disconnected'>((resolve) => |
| 23 | + setTimeout(() => resolve('disconnected'), config.HEALTH_DB_TIMEOUT_MS), |
| 24 | + ); |
17 | 25 |
|
18 | | - let database: 'connected' | 'disconnected'; |
19 | | - try { |
20 | | - database = await Promise.race([pingDatabase(c.env.HYPERDRIVE), timeout]); |
21 | | - } catch { |
22 | | - database = 'disconnected'; |
23 | | - } |
| 26 | + let database: 'connected' | 'disconnected'; |
| 27 | + try { |
| 28 | + database = await Promise.race([pingDatabase(c.env.HYPERDRIVE), timeout]); |
| 29 | + } catch { |
| 30 | + database = 'disconnected'; |
| 31 | + } |
24 | 32 |
|
25 | | - const status = database === 'connected' ? 'healthy' : 'unhealthy'; |
26 | | - const body = { |
27 | | - status, |
28 | | - version: c.env.APP_VERSION ?? 'unknown', |
29 | | - uptime: Math.floor((Date.now() - startTime) / 1000), |
30 | | - timestamp: new Date().toISOString(), |
31 | | - requestId: c.get('requestId'), |
32 | | - checks: { database }, |
33 | | - }; |
34 | | - return c.json(body, status === 'healthy' ? 200 : 503); |
35 | | -}); |
| 33 | + const status = database === 'connected' ? 'healthy' : 'unhealthy'; |
| 34 | + const body = { |
| 35 | + status, |
| 36 | + version: config.APP_VERSION, |
| 37 | + uptime: Math.floor((Date.now() - startTime) / 1000), |
| 38 | + timestamp: new Date().toISOString(), |
| 39 | + requestId: c.get('requestId'), |
| 40 | + checks: { database }, |
| 41 | + }; |
| 42 | + return c.json(body, status === 'healthy' ? 200 : 503); |
| 43 | + }, |
| 44 | +); |
0 commit comments