Get data from observable grpc service in nestjs,
Asked Answered
A

2

5

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] }
Apotheosize answered 20/6, 2020 at 13:2 Comment(0)
B
13

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.

Balladmonger answered 20/6, 2020 at 13:32 Comment(4)
This is now replaced with firstValueFrom and lastValueFrom. Will be removed in v8. Details: rxjs.dev/deprecations/to-promiseSeigniory
@Nils: True, feel free to edit my answer :)Balladmonger
It tells me that the "Suggested edit queue is full". (I also did not know I could edit answers, thanks :)Seigniory
github.com/yukukotani/protoc-gen-nestjs/blob/… In shortly you need to write stream keyword before your return type in proto files.Suckow
K
3

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)));
  }
Kidwell answered 20/6, 2020 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.