Get data from observable grpc service in nestjs,

Viewed 2976

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] }
2 Answers

One way to do this is to convert your Observable to a Promise 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 this.heroService.findOne({ id: +id }).toPromise();
  
  res.name = res.name + 'modify string'; 

  return res;

}

Note: If you want to stick to Observable use bharat1226's solution.

Your can use map operator to transform the emitted value.

In the below code, you are adding string modify string to name.

@Get(':id')
  getById(@Param('id') id: string): Observable<Hero> {
    return this.heroService
      .findOne({ id: +id })
      .pipe(map(item => ({ ...item, name: `${item.name}modify string` })));
  }

If any time, you want to log emitted values or perform side effects in an Observable stream, you can use tap operator

@Get(':id')
  getById(@Param('id') id: string): Observable<Hero> {
    return this.heroService
      .findOne({ id: +id })
      .pipe(tap(item => console.log(item)));
  }
Related