Leung-JZ
Leung-JZ

Reputation: 3

How can i access the database into the middleware

I want to record the frequency of accessing the API. I want to insert every API access directly into the database through middleware. I don't know how to access the database in nestjs middleware.

The code will like:

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

// console.log('StatisticsMiddleware');
@Injectable()
export class StatisticsMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    // console.log(req.originalUrl, req.ip, req.connection.remoteAddress);
    const url = req.originalUrl
    const ip = req.ip || req.connection.remoteAddress

    // 
    Db.insert('LOG_TABLE', url, ip)
    next();
  }
}

Upvotes: 0

Views: 2294

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70101

A middleware class is just like any other @Injectable() class in NestJS, and as such can have the database injected into it. The docs mention you can use injection like any other provider, so all you'll need to do is provide your database connection (be it a Mongo Model, a TypeORM Repository, or anything else) and you'll be good to access from there.

Upvotes: 1

Related Questions