Server-Timing 中間件
Server-Timing 中間件在回應標頭中提供效能指標。
資訊
注意:在 Cloudflare Workers 上,計時器指標可能不準確,因為計時器僅顯示最後一次 I/O 的時間。
導入
ts
import { Hono } from 'hono'
import { timing, setMetric, startTime, endTime } from 'hono/timing'
import type { TimingVariables } from 'hono/timing'
用法
js
// Specify the variable types to infer the `c.get('metric')`:
type Variables = TimingVariables
const app = new Hono<{ Variables: Variables }>()
// add the middleware to your router
app.use(timing());
app.get('/', async (c) => {
// add custom metrics
setMetric(c, 'region', 'europe-west3')
// add custom metrics with timing, must be in milliseconds
setMetric(c, 'custom', 23.8, 'My custom Metric')
// start a new timer
startTime(c, 'db');
const data = await db.findMany(...);
// end the timer
endTime(c, 'db');
return c.json({ response: data });
});
條件啟用
ts
const app = new Hono()
app.use(
'*',
timing({
// c: Context of the request
enabled: (c) => c.req.method === 'POST',
})
)
結果
選項
可選 total: boolean
顯示總回應時間。預設值為 true
。
可選 enabled: boolean
| (c: Context) => boolean
是否應將計時新增至標頭。預設值為 true
。
可選 totalDescription: boolean
總回應時間的描述。預設值為 Total Response Time
。
可選 autoEnd: boolean
是否應在請求結束時自動結束 startTime()
。如果停用,則不會顯示未手動結束的計時器。
可選 crossOrigin: boolean
| string
| (c: Context) => boolean | string
這個計時標頭應該可讀取的來源。
- 如果為 false,則僅來自目前來源。
- 如果為 true,則來自所有來源。
- 如果為字串,則來自此網域。多個網域必須以逗號分隔。
預設值為 false
。請參閱更多文件。