nest
nest copied to clipboard
gRPC Request info in Execution Context
Is there an existing issue that is already proposing this?
- [X] I have searched the existing issues
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',
]
}
-
GrpcMethodStreamingType
: Already exists in the codebase, it just isn't referenced or apparent to use. - Pattern object: Indirectly defined in codebase but has no referencing type.
-
Metadata
: Import from@grpc/grpc-js
and the standard metadata object for use in Nest rpc microservices -
RpcContext
: Modeled after the args array returned bycontext.switchToRpc()
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.
Would you like to create a PR for this issue?
Busy with my 9-5 at the moment, but if I get some free time soon I'll take a look.
I would like to work on this issue
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.