'How to send response from middleware created in a Nest fastify server?
I've created a NestJs project with Fastify, and have created a middleware for it, but I can't figure out how to send a response to the client, similar to how we could do in express, any help would be appreciated, thanks!, here's my middleware code:
import {
Injectable,
NestMiddleware,
HttpException,
HttpStatus,
} from '@nestjs/common';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: any, res: any, next: Function) {
console.log('Request...', res);
// throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
next();
}
}
Solution 1:[1]
Looks like Fastify
abstraction uses NodeJS vanila http
objects (The res
injected here is http,ServerResponse )
// app.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { ServerResponse, IncomingMessage } from 'http';
@Injectable()
export class AppMiddleware implements NestMiddleware {
use(req: IncomingMessage, res: ServerResponse, next: Function) {
res.writeHead(200, { 'content-type': 'application/json' })
res.write(JSON.stringify({ test: "test" }))
res.end()
}
}
// app.module.ts
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppMiddleware } from './app.middleware';
@Module({
imports: [],
controllers: [AppController],
providers: [],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AppMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL }); // apply on all routes
}
}
Solution 2:[2]
An example with adaptation of Daniel code to kill execution after middleware validations (cache) using express
import { BadRequestException, Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class CacheMiddleware implements NestMiddleware {
constructor(
private cacheService: CacheService
){}
async use(req: Request, res: Response, next: NextFunction) {
const cache = await this.cacheService.getCache(req.url)
if(cache){
res.writeHead(200, { 'content-type': 'application/json' })
res.write(cache)
res.end()
return
}
next();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |