|
| 1 | +import type { NextApiRequest } from 'next' |
| 2 | +import * as OS from 'os' |
| 3 | + |
| 4 | +/* --- Constants ------------------------------------------------------------------------------- */ |
| 5 | + |
| 6 | +const ALIVE_SINCE = new Date() |
| 7 | + |
| 8 | +/* --- Types ----------------------------------------------------------------------------------- */ |
| 9 | + |
| 10 | +type HealthCheckArgs = { |
| 11 | + echo: string |
| 12 | + req: Request | NextApiRequest |
| 13 | +} |
| 14 | + |
| 15 | +/** --- healthCheck() -------------------------------------------------------------------------- */ |
| 16 | +/** -i- Check the health status of the server. Includes relevant urls, server time(zone), versions and more */ |
| 17 | +export const healthCheck = async (args: HealthCheckArgs) => { |
| 18 | + // Input |
| 19 | + const { echo, req } = args |
| 20 | + |
| 21 | + // Vars |
| 22 | + const now = new Date() |
| 23 | + const aliveTime = now.getTime() - ALIVE_SINCE.getTime() |
| 24 | + |
| 25 | + // Urls |
| 26 | + const r = req as Request |
| 27 | + const rn = req as NextApiRequest |
| 28 | + const reqHost = rn?.headers?.host |
| 29 | + const reqProtocol = rn?.headers?.['x-forwarded-proto'] ?? 'http' |
| 30 | + const requestURL = r?.url ?? `${reqProtocol}://${reqHost}/api/health` |
| 31 | + const baseURL = process.env.BACKEND_URL || requestURL?.split('/api/')[0] |
| 32 | + const apiURL = baseURL ? `${baseURL}/api` : null |
| 33 | + |
| 34 | + // -- Respond -- |
| 35 | + |
| 36 | + return { |
| 37 | + // PARAMS |
| 38 | + echo, |
| 39 | + // STATUS |
| 40 | + status: 'OK', |
| 41 | + alive: true, |
| 42 | + kicking: true, |
| 43 | + // TIME & DATES |
| 44 | + now: now.toISOString(), |
| 45 | + aliveTime, |
| 46 | + aliveSince: ALIVE_SINCE.toISOString(), |
| 47 | + serverTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 48 | + // URLS |
| 49 | + requestURL, |
| 50 | + baseURL, |
| 51 | + apiURL, |
| 52 | + port: process.env.PORT ? Number(process.env.PORT) : null, |
| 53 | + debugPort: process.debugPort && Number(process.debugPort), |
| 54 | + // VERSIONS |
| 55 | + nodeVersion: process.versions.node, |
| 56 | + v8Version: process.versions.v8, |
| 57 | + // SYSTEM |
| 58 | + systemArch: OS.arch(), |
| 59 | + systemPlatform: OS.platform(), |
| 60 | + systemRelease: OS.release(), |
| 61 | + systemFreeMemory: OS.freemem(), |
| 62 | + systemTotalMemory: OS.totalmem(), |
| 63 | + systemLoadAverage: OS.loadavg(), |
| 64 | + } |
| 65 | +} |
0 commit comments