看起来Fastify
抽象使用 NodeJS vanilahttp
对象(这里res
注入的是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
}
}