Created
December 22, 2022 01:52
-
-
Save myesn/ec9fbb3a1e91c210a4dcb833da9d44ad to your computer and use it in GitHub Desktop.
NestJS Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// logging.middleware.ts | |
import { Injectable, NestMiddleware } from '@nestjs/common'; | |
import { NextFunction, Request, Response } from 'express'; | |
@Injectable() | |
export class LoggingMiddleware implements NestMiddleware { | |
use(req: Request, res: Response, next: NextFunction) { | |
console.log(`start [${req.method}] ${req.url}`); | |
const oldSend = res.send; | |
res.send = (body: any): any => { | |
console.log(body); | |
oldSend.call(res, body); | |
}; | |
next(); | |
console.log(`end [${req.method}] ${req.url}`); | |
} | |
} | |
// main.ts | |
async function bootstrap() { | |
app.use(new LoggingMiddleware().use); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment