53 lines
2.0 KiB
TypeScript
53 lines
2.0 KiB
TypeScript
import { Catch, HttpException, Injectable } from "@nestjs/common";
|
|
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
|
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
import { randomUUID } from "node:crypto";
|
|
|
|
@Injectable()
|
|
export class RequestIdMiddleware {
|
|
use(request: FastifyRequest, reply: FastifyReply, next: () => void): void {
|
|
const requestId = request.headers["x-request-id"]?.toString() ?? randomUUID();
|
|
if (typeof reply.header === "function") {
|
|
reply.header("x-request-id", requestId);
|
|
} else {
|
|
(reply as unknown as { setHeader: (name: string, value: string) => void }).setHeader(
|
|
"x-request-id",
|
|
requestId,
|
|
);
|
|
}
|
|
(request as FastifyRequest & { requestId?: string }).requestId = requestId;
|
|
if (process.env.NODE_ENV === "development") {
|
|
console.info("api request", { method: request.method, url: request.url, requestId });
|
|
}
|
|
next();
|
|
}
|
|
}
|
|
|
|
@Catch()
|
|
export class ApiExceptionFilter implements ExceptionFilter {
|
|
catch(exception: unknown, host: ArgumentsHost): void {
|
|
const context = host.switchToHttp();
|
|
const response = context.getResponse<FastifyReply>();
|
|
const request = context.getRequest<FastifyRequest>();
|
|
const status = exception instanceof HttpException ? exception.getStatus() : 500;
|
|
if (!(exception instanceof HttpException)) console.error("api unhandled error", exception);
|
|
const detail =
|
|
exception instanceof HttpException
|
|
? exception.getResponse()
|
|
: process.env.NODE_ENV === "development" && exception instanceof Error
|
|
? exception.message
|
|
: "服务器内部错误";
|
|
response.status(status).send({
|
|
data: null,
|
|
error: {
|
|
code: `HTTP_${status}`,
|
|
message: typeof detail === "string" ? detail : "请求失败",
|
|
},
|
|
requestId:
|
|
(request as FastifyRequest & { requestId?: string }).requestId ??
|
|
request.headers["x-request-id"] ??
|
|
null,
|
|
});
|
|
}
|
|
}
|