feat: add api http conventions and booking state rules

This commit is contained in:
que01 committed 2026-09-18 17:17:47 +08:00
1 parent 0d4caaba00
commit 0e8b8e1591
5 files changed
+61

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
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();
reply.header("x-request-id", 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;
const detail = exception instanceof HttpException ? exception.getResponse() : "服务器内部错误";
response.status(status).send({
data: null,
error: {
code: `HTTP_${status}`,
message: typeof detail === "string" ? detail : "请求失败",
},
requestId: request.headers["x-request-id"] ?? null,
});
}
}