I have an issue when I create a Nest microservices controller where I cannot retrieve the Subject of the sent message. For example, I am setting up a NATS service with a wildcard subscription for the pattern time.us.*. Here's an example of handling the subject from the docs:
await nc.subscribe('time.us.*', (err, msg) => {
let time = "";
switch (msg.subject) {
case 'time.us.east':
time = new Date().toLocaleTimeString("en-us", {timeZone: "America/New_York"});
break;
case 'time.us.central':
time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Chicago"});
break;
case 'time.us.mountain':
time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Denver"});
break;
case 'time.us.west':
time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Los_Angeles"});
break;
default:
time = "I don't know what you are talking about Willis";
}
console.log(msg.subject, time);
});
In my Nest NATS controller, I can set up the following controller function:
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
) {}
@MessagePattern('time.us.*'')
getTime(data: any, blah: any) {
// can get only data from the message, not subject
return `the time is ${Date.now()}`
}
}
I would like a way to access the subject of the received message, possibly through a second parameter in the @MessagePattern decorated function,
Wildcard subscriptions are an important part of NATS (and probably other transports, but I am not familiar with others). Without this feature, the Nest implementation is essentially a non-starter.
We should expose access to the underlying, native properties within events/messages handlers. Thanks for reporting!
As far as I know, for now, it just uses the .subscribe provided by Nats.
https://github.com/nestjs/nest/blob/35c79bd4915786cc9dc94ab4170c031c1a9819d5/packages/microservices/server/server-nats.ts#L44
We could provide a second parameter to the Message Handler when it's about a wildcard, so we can retrieve the base message.
A simple solution could be to check if there is a .subject, and pass it to the handler here: https://github.com/nestjs/nest/blob/35c79bd4915786cc9dc94ab4170c031c1a9819d5/packages/microservices/server/server-nats.ts#L108
Does it cause breaking change? If not, I could try to open a PR on this.
This PR https://github.com/nestjs/nest/pull/3039 will solve this issue
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
We should expose access to the underlying, native properties within events/messages handlers. Thanks for reporting!