import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private readonly logger = new Logger(LoggerMiddleware.name);

  use(req: Request, res: Response, next: () => void): void {
    this.logger.log(this.createReqMsg(req));

    res.on('close', () => {
      this.logger.log(this.createResMsg(res));
    });
    next();
  }

  private createReqMsg(req: Request): string {
    const message = `Request [url=${req.url}, method=${req.method}]`;

    return message;
  }

  private createResMsg(res: Response): string {
    const message = `Response [statusCode=${res.statusCode}, message=${res.statusMessage}]`;

    return message;
  }
}
