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
68.22k stars 7.67k forks source link

gRPC Request info in Execution Context #10275

Closed Jake-RoundrockIO closed 3 weeks ago

Jake-RoundrockIO commented 2 years ago

Is there an existing issue that is already proposing this?

Is your feature request related to a problem? Please describe it

When creating working gRPC microservices I would like to be able to access information about the request (i.e. Service and Pattern) through the Execution Context argument that is exposed in things like guard, interceptors, etc... This info currently only resides in the injected request object only visible in request-scoped injectables.

Describe the solution you'd like

Ideally the service/pattern info available in the request object should also exist in the context object. This could be as simple as adding the pattern property of the request object to the context as-is. It would also be nice to have some better typings around gRPC microservices as I couldn't find a typing for the Request object exposed in gRPC microservices as well, so it took some trial and error just to figure out where and that there even was pattern related data exposed for rpc endpoints.

Teachability, documentation, adoption, migration strategy

Pseudocode depiction of the types for request and new context object would be as follows:

type GrpcRequest = {
  pattern: {
    service: string;
    rpc: string;
    streaming: GrpcMethodStreamingType
  },
  data: any;
  context: Metadata;
}
type RpcContext = {
  args: [
    data: any,
    context: Metadata & Pattern,
    ...,
    contextType: 'rpc',   
  ]
}

What is the motivation / use case for changing the behavior?

The motivation for this feature request is to allow developers to access the pattern details of rpc requests without having to make injectables request-scoped.

kamilmysliwiec commented 1 year ago

Would you like to create a PR for this issue?

Jake-RoundrockIO commented 1 year ago

Busy with my 9-5 at the moment, but if I get some free time soon I'll take a look.

vijayabhaskar-ev commented 1 year ago

I would like to work on this issue

ssilve1989 commented 10 months ago

Maybe I'm misunderstanding something, but where I work I implemented this a long time ago and doesn't require, to my knowledge, the injectables to be request scoped. You can do

    const metadata = this.reflector.get<unknown>(PATTERN_METADATA, context.getHandler());
    return Array.isArray(metadata) ? metadata[0] : ({} as GrpcMetadata);

to get

{
  rpc: string;
  service: string;
  streaming: GrpcMethodStreamingType;
}

since this is operating on the perspective of the handler being invoked, not the request.