Search code examples
nestjstypeorm

NestJs include TypeORM repository in middleware


I have the following middleware to log all http requests:

@Injectable()
export class RequestMiddleware implements NestMiddleware {
  constructor(
    @InjectRepository(Request) private requestsRepository: Repository<Request>,
  ) {}
  private readonly logger = new Logger('HTTP');

  use(request: Request, response: Response, next: NextFunction) {
    response.on('finish', () => {
      const { method, originalUrl } = request;
      const { statusCode, statusMessage } = response;
      const message = `${method} ${originalUrl} ${statusCode} ${statusMessage}`;
      return this.logger.log(message);
    });
    next();
  }
}

My goal is to log all requests to a database. I am using TypeORM so I would like to inject the Request repository and log each request that way. When I do this I receive the following error:

Error: Nest can't resolve dependencies of the class RequestMiddleware

The issue is that this middleware isn't part of a module, it's just a single typescript file so how do I import the TypeORM repo module into a normal typescript file so I can use it?


Solution

  • In the module where RequestMiddleware is defined and used, TypeormModule.forFeature([Request]) needs to be added to the imports array