主要.ts
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { Logger } from 'nestjs-pino';
import { AppModule } from './app.module';
import { ConfigService } from './utils/config/config.service';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
app.enableCors({ credentials: true, origin: true });
app.useLogger(app.get(Logger));
app.useGlobalPipes(new ValidationPipe());
app.connectMicroservice({
transport: Transport.NATS,
options: {
servers: [process.env.NATS_SERVER_URL!],
queue: 'PLAYER',
},
});
const configService = app.get(ConfigService);
await app.startAllMicroservices();
await app.listen(configService.port, '0.0.0.0');
console.log(`Gateway is running on: ${await app.getUrl()}`);
}
bootstrap();
拦截器.module.ts
import { APP_INTERCEPTOR } from '@nestjs/core';
import { UuidInterceptor } from './uuid.interceptor';
import { RetryInterceptor } from './retry.interceptor';
import { TimeoutInterceptor } from './timeout.interceptor';
import { LoggerErrorInterceptor } from 'nestjs-pino';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: UuidInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: RetryInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: TimeoutInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: LoggerErrorInterceptor,
},
],
})
export class InterceptorsModule {}
我创建了几个拦截器并将它们包含在interceptors.module.ts中,并将其导入到app.module.ts中。然而,当我提出任何要求时,他们似乎都没有被叫到。
我尝试在 useGlobalInterceptors 的 main.ts 中专门添加拦截器,但我也没有工作
您应该在 connectMicroservice 函数中设置 NestHybridApplicationOptions
例如
async function bootstrap() {
const appOptions = { logger: new NestLogger('', true, 'WebApiGateway') };
const app = await NestFactory.create<NestApplication>(AppModule, appOptions);
app.useGlobalInterceptors(new TcpInterceptor());
const config = app.get<ConfigService>(ConfigService);
const port = config.get('port');
app.connectMicroservice<TcpClientOptions>(
{
transport: Transport.TCP,
options: { port, host: '0.0.0.0' }
},
{
inheritAppConfig: true
}
);
await app.startAllMicroservices();
Logger.log(`Application started and listening on ${port}!!!`, 'MainBootstrap');
}