mirror of
https://github.com/DIYgod/RSSHub.git
synced 2026-09-01 14:57:14 +08:00
08a38f0a5e
* refactor: typing house-keeping * fix: fix parse date not accepting strict mode * refactor: use npm package * fix: address review
46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import type { MiddlewareHandler } from 'hono';
|
|
|
|
import { getPath, time } from '@/utils/helpers';
|
|
import logger from '@/utils/logger';
|
|
import { requestMetric } from '@/utils/otel';
|
|
|
|
enum LogPrefix {
|
|
Outgoing = '-->',
|
|
Incoming = '<--',
|
|
Error = 'xxx',
|
|
}
|
|
|
|
const colorStatus = (status: number) => {
|
|
const out = new Map<number, string>([
|
|
[7, `\u{1B}[35m${status}\u{1B}[0m`],
|
|
[5, `\u{1B}[31m${status}\u{1B}[0m`],
|
|
[4, `\u{1B}[33m${status}\u{1B}[0m`],
|
|
[3, `\u{1B}[36m${status}\u{1B}[0m`],
|
|
[2, `\u{1B}[32m${status}\u{1B}[0m`],
|
|
[1, `\u{1B}[32m${status}\u{1B}[0m`],
|
|
[0, `\u{1B}[33m${status}\u{1B}[0m`],
|
|
]);
|
|
|
|
const calculateStatus = Math.trunc(status / 100);
|
|
|
|
return out.get(calculateStatus);
|
|
};
|
|
|
|
const middleware: MiddlewareHandler = async (ctx, next) => {
|
|
const { method, raw, routePath } = ctx.req;
|
|
const path = getPath(raw);
|
|
|
|
logger.info(`${LogPrefix.Incoming} ${method} ${path}`);
|
|
|
|
const start = Date.now();
|
|
|
|
await next();
|
|
|
|
const status = ctx.res.status;
|
|
|
|
logger.info(`${LogPrefix.Outgoing} ${method} ${path} ${colorStatus(status)} ${time(start)}`);
|
|
requestMetric.success(Date.now() - start, { path: routePath, method, status });
|
|
};
|
|
|
|
export default middleware;
|