Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions api/health.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { NUM, OBJ, STR } from '@01edu/api/validator'
import { route } from '@01edu/api/router'
import { now, startTime } from '@01edu/time'
import { CI_COMMIT_SHA } from '@01edu/api/env'

/**
* Creates a health check route that returns the application's status, uptime, version, and instance ID.
*
* @example
* ```ts
* import { makeRouter, route } from '@01edu/router';
* import { createHealthRoute } from '@01edu/api/health';
*
* const routes = {
* 'GET/api/health': createHealthRoute(),
* };
*
* const router = makeRouter(routes,{});
* ```
*
* @returns A route handler for the health check endpoint.
*/
export const createHealthRoute = () => {
return route({
output: OBJ({
status: STR(),
timestamp: STR(),
uptime: NUM(),
version: STR(),
instanceId: STR(),
}),
fn: () => {
return {
status: 'ok',
timestamp: new Date().toISOString(),
uptime: now() - startTime,
version: CI_COMMIT_SHA || 'unknown',
instanceId: startTime.toString(),
}
},
})
}
5 changes: 5 additions & 0 deletions api/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { respond, ResponseError } from './response.ts'
import type { Sql } from '@01edu/types/db'
import { createSqlDevRoute } from './dev.ts'
import { createDocRoute } from './doc.ts'
import { createHealthRoute } from './health.ts'

/**
* Options for configuring the router.
Expand Down Expand Up @@ -134,6 +135,10 @@ export const makeRouter = <T extends GenericRoutes>(
defs['GET/api/doc'] = createDocRoute(defs)
}

if (!defs['GET/api/health']) {
defs['GET/api/health'] = createHealthRoute()
}

for (const key in defs) {
const slashIndex = key.indexOf('/')
const method = key.slice(0, slashIndex) as HttpMethod
Expand Down