|
| 1 | +import { Injectable, NestMiddleware } from "@nestjs/common"; |
| 2 | +import { NextFunction, Request, Response } from "express"; |
| 3 | + |
| 4 | +import { PrismaService } from "src/modules/prisma/prisma.service"; |
| 5 | + |
| 6 | +@Injectable() |
| 7 | +export class RequestLoggerMiddleware implements NestMiddleware { |
| 8 | + constructor(private readonly prisma: PrismaService) {} |
| 9 | + |
| 10 | + async use(req: Request, res: Response, next: NextFunction) { |
| 11 | + const start = Date.now(); |
| 12 | + |
| 13 | + // Intercept the response to capture the body |
| 14 | + const originalSend = res.send; |
| 15 | + let responseBody: unknown; |
| 16 | + |
| 17 | + res.send = (body): Response => { |
| 18 | + responseBody = body; // Capture the response body |
| 19 | + return originalSend.call(res, body); // Call the original `send` method |
| 20 | + }; |
| 21 | + |
| 22 | + // Attach an event listener to log after the response is sent |
| 23 | + res.on("finish", async () => { |
| 24 | + const duration = Date.now() - start; |
| 25 | + const { |
| 26 | + method, |
| 27 | + url: path, |
| 28 | + headers: { "user-agent": userAgent = null }, |
| 29 | + } = req; |
| 30 | + const { statusCode } = res; |
| 31 | + const responseString = |
| 32 | + typeof responseBody === "string" |
| 33 | + ? responseBody |
| 34 | + : JSON.stringify(responseBody); |
| 35 | + |
| 36 | + const ignoreResponse = [ |
| 37 | + "/v1/stop/all", |
| 38 | + "/v1/platform/", |
| 39 | + "/status", |
| 40 | + ].some((item) => path.startsWith(item)); |
| 41 | + |
| 42 | + try { |
| 43 | + // Log the request details to the database |
| 44 | + await this.prisma.requestLog.create({ |
| 45 | + data: { |
| 46 | + method, |
| 47 | + path, |
| 48 | + status: statusCode, |
| 49 | + duration, |
| 50 | + userAgent, |
| 51 | + response: ignoreResponse ? null : responseString, |
| 52 | + }, |
| 53 | + }); |
| 54 | + } catch (error) { |
| 55 | + console.error("Failed to log request:", error); |
| 56 | + } |
| 57 | + }); |
| 58 | + |
| 59 | + next(); |
| 60 | + } |
| 61 | +} |
0 commit comments