14. Simple Healthz Controller
Simple Healthz Controller
เรามาเริ่มทำ controller แบบง่ายๆกันก่อน เป็น path /healthz
เอาไว้ทำ Health check แบบง่ายๆ
src/controllers/healthz.ts
import { Schema as S } from "effect"import { Hono } from "hono"import { describeRoute } from "hono-openapi"import { resolver } from "hono-openapi/effect"
const responseSchema = S.Struct({ message: S.Literal("Ok"),})
const doc = describeRoute({ description: "Are we healthy?", responses: { 200: { content: { "application/json": { schema: resolver(responseSchema), }, }, description: "Healthy", }, },})
const healthzApp = new Hono()
healthzApp.get("/", doc, (c) => { return c.json({ message: "Ok", }, 200)})
export default healthzApp
เราจะสร้าง doc ขึ้นมาก่อน ผ่าน describeRoute()
ซึ่งในนี้จะเป็นการใส่ข้อมูลเกี่ยวกับ Response อย่างเดียว
ซึ่งมีโครงสร้างตามที่เห็น
object responses
ต้องใส่ object ซึ่งใช้ key ที่เป็น HttpStatus เช่น 200
, 201
, 404
, 500
describeRoute({ responses: { 200: {}, 404: {}, },})
แล้วตามด้วย content
describeRoute({ description: "Are we healthy?", responses: { 200: { content: {}, }, 404: { content: {}, }, },})
ภายใน object content
จะต้องเป็น content type เป็นอะไร เช่น application/json
, text/plain
, text/html
describeRoute({ description: "Are we healthy?", responses: { 200: { content: { "application/json": {}, }, }, },})
แล้วเราก็จะใส่ schema
เข้าไป
ตรง schema
นี้เราจะใช้ Effect Schema อีกเช่นเคย ตรงนี้ต้องใส่ resolver()
ด้วย เพื่อไปเรียกคำสั่งแปลง Effect Schema ให้ไปเป็น JsonSchema
describeRoute({ description: "Are we healthy?", responses: { 200: { content: { "application/json": { schema: resolver(responseSchema), }, }, }, },})
สุดท้ายใน doc ต้องอย่าลืมใส่ description
ด้วย
describeRoute({ description: "Are we healthy?", responses: { 200: { content: { "application/json": { schema: resolver(responseSchema), }, }, description: "Healthy", }, },})
จากตัวอย่างด้านบนเราจะ new Hono()
ใหม่เลย ทำให้เราได้ hono app ตัวใหม่ออกมาเลย
จากนั้นก็ใส่ .get("/")
จะเห็นว่าใช้ paht ”/” เฉยๆเลย ตรงนี้เรายังไม่ต้องสนใจว่าจะใช้ path อะไร เดี๋ยวเราไปกำหนดตอนที่ต้องเรียกใช้
ที่ index.ts
อีกที
แล้วเราก็ export Hono app ตัวใหม่ออกมา
use healthz controller in index.ts
ตรงนี้เราจะเอา Hono app ตัวใหม่มาใส่ที่ Hono app ตัวหลักของเรา ผ่าน .route(<path>, <hono app>)
แล้วเราจะกำหนดตรงนี้แหละว่า path ที่ใช้กับ Hono app ตัวใหม่เป็นอะไร
src/index.ts
const app = new Hono()setupOpenApi(app)
app.route("/docs", setupScalarDocs())
app.route("/healthz", healthzApp)