chore: add http logger and core interceptors
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
|
||||
import { FastifyReply, FastifyRequest } from "fastify";
|
||||
|
||||
@Catch(HttpException)
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: HttpException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const reply = ctx.getResponse<FastifyReply>();
|
||||
const request = ctx.getRequest<FastifyRequest>();
|
||||
const status = exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
|
||||
const exceptionResponse = exception.getResponse();
|
||||
const message = this.extractMessage(exceptionResponse);
|
||||
|
||||
reply.status(status).send({
|
||||
statusCode: status,
|
||||
success: false,
|
||||
error: {
|
||||
message,
|
||||
// timestamp: new Date().toISOString(),
|
||||
path: request.url,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private extractMessage(response: string | Record<string, any>): string | string[] {
|
||||
if (typeof response === "string") {
|
||||
return [response];
|
||||
}
|
||||
|
||||
if (typeof response === "object" && "message" in response) {
|
||||
return Array.isArray(response.message) ? response.message : [response.message];
|
||||
}
|
||||
|
||||
return "something wrong";
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
||||
import { Response } from "express";
|
||||
import { FastifyReply } from "fastify";
|
||||
import { Observable } from "rxjs";
|
||||
import { map } from "rxjs/operators";
|
||||
|
||||
@@ -7,7 +7,7 @@ import { map } from "rxjs/operators";
|
||||
export class ResponseInterceptor implements NestInterceptor {
|
||||
//
|
||||
intercept(context: ExecutionContext, next: CallHandler<Record<string, unknown>>): Observable<unknown> {
|
||||
const ctx = context.switchToHttp().getResponse<Response>();
|
||||
const ctx = context.switchToHttp().getResponse<FastifyReply>();
|
||||
const statusCode = ctx.statusCode;
|
||||
|
||||
return next.handle().pipe(
|
||||
|
||||
@@ -1,24 +1,26 @@
|
||||
// import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
|
||||
// import { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
|
||||
import { FastifyReply, FastifyRequest } from "fastify";
|
||||
|
||||
// @Injectable()
|
||||
// export class HTTPLoggerMiddleware implements NestMiddleware {
|
||||
// private readonly logger = new Logger(HTTPLoggerMiddleware.name);
|
||||
// // use(req: any, res: any, next: (error?: Error | any) => void) {}
|
||||
@Injectable()
|
||||
export class HTTPLogger implements NestMiddleware {
|
||||
private readonly logger = new Logger(HTTPLogger.name);
|
||||
// use(req: any, res: any, next: (error?: Error | any) => void) {}
|
||||
|
||||
// use(req: FastifyRequest, res: FastifyReply, next: NextFunction) {
|
||||
// const { ip, method, baseUrl } = req;
|
||||
// const userAgent = req.get("user-agent") || "";
|
||||
// const startAt = process.hrtime();
|
||||
use(req: FastifyRequest, rep: FastifyReply["raw"], next: () => void) {
|
||||
const { ip, method, originalUrl } = req;
|
||||
const userAgent = req.headers["user-agent"] || "";
|
||||
const startAt = process.hrtime();
|
||||
|
||||
// res.on("finish", () => {
|
||||
// const { statusCode } = res;
|
||||
// const contentLength = res.get("content-length") || 0;
|
||||
// const dif = process.hrtime(startAt);
|
||||
// const responseTime = dif[0] * 1e3 + dif[1] * 1e-6;
|
||||
// this.logger.log(`${method} - ${baseUrl} - ${statusCode} - ${contentLength} - ${userAgent} - ${ip} - ${responseTime.toFixed(2)}ms`);
|
||||
// });
|
||||
rep.on("finish", () => {
|
||||
const { statusCode } = rep;
|
||||
const contentLength = rep.getHeader("content-length") || 0;
|
||||
const dif = process.hrtime(startAt);
|
||||
const responseTime = dif[0] * 1e3 + dif[1] * 1e-6;
|
||||
this.logger.log(
|
||||
`${method} - ${originalUrl} - ${statusCode} - ${contentLength} - ${userAgent} - ${ip} - ${responseTime.toFixed(2)}ms`,
|
||||
);
|
||||
});
|
||||
|
||||
// next();
|
||||
// }
|
||||
// }
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user