nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.29k stars 7.59k forks source link

Global Interceptors not executed in RPC / GRPC context #6869

Closed sjkummer closed 3 years ago

sjkummer commented 3 years ago

Bug Report

Current behavior

Global interceptors are not called for GRPC methods (probably the same for all RPC methods).

Input Code

I added the logging.interceptor.ts example from https://docs.nestjs.com/interceptors#aspect-interception to sample/04-grpc of this repo.

const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new LoggingInterceptor());

Current behavior

The logging interceptor is executed, if I call the REST method e.g. http://localhost:3001/hero/1 but NOT if I call the GRPC method.

Expected behavior

Interceptors should be executed in all contexts.

Possible Solution

I can get the global GRPC interceptor working by doing two things (both must be done, otherwise it's not working):

  1. Changing the rpc-context-creator.js as follows: Line L124ff: https://github.com/nestjs/nest/blob/master/packages/microservices/context/rpc-context-creator.ts#L124

        return this.rpcProxy.create(async (...args) => {
    
            const initialArgs = this.contextUtils.createNullArray(argsLength);
            fnCanActivate && (await fnCanActivate(args));
    
            // REMOVED:
            //return this.interceptorsConsumer.intercept(interceptors, args, instance, callback, handler(initialArgs, args), contextType);
    
            // ADDED:
            const runtimeInterceptors = this.interceptorsContextCreator.create(instance, callback, module, contextId, inquirerId);
            return this.interceptorsConsumer.intercept(runtimeInterceptors, args, instance, callback, handler(initialArgs, args), contextType);
    
        }, exceptionHandler);

    Background: The interceptors are only set in create() ... but they are empty at this time - although useGlobalInterceptors is called directly after NestFactory.create()

  2. Calling connectMicroservice with inheritAppConfig

    app.connectMicroservice<MicroserviceOptions>(grpcClientOptions, {
    inheritAppConfig: true
    });

    This shouldn't e required right? But if yes, then it should be documented.

Environment


Nest version: 7.6.15
jmcdo29 commented 3 years ago

The inheritAppConfig is expected, and is documented here. If that alone doesn't fix it, please provide a minimum reproduction

sjkummer commented 3 years ago

Thanks for that doc link 🙌

I confirm, setting inheritAppConfig is sufficient in a clean setup.