I want to use gRPC service to communicate between my microservices. but when getting a response from Grpc service, before return a method, I want to do some modification and functionality.
sample project: https://github.com/nestjs/nest/tree/master/sample/04-grpc
like this:
@Get(':id')
getById(@Param('id') id: string): Observable<Hero> {
const res: Observable<Hero> = this.heroService.findOne({ id: +id });
console.log(res); res.name = res.name + 'modify string';
return res;
}
but show below message in console.log instead of the original response.
Observable { _isScalar: false, _subscribe: [Function] }
One way to do this is to convert your Observable
to a Promise
using e.g. lastValueFrom
and await this promise. You can then modify and return the result:
@Get(':id')
async getById(@Param('id') id: string): Promise<Hero> {
const res:Hero = await lastValueFrom(this.heroService.findOne({ id: +id }));
res.name = res.name + 'modify string';
return res;
}
Note: If you want to stick to Observable
use bharat1226's solution.