MCPcopy
hub / github.com/nestjs/nest / HeroController

Class HeroController

sample/04-grpc/src/hero/hero.controller.ts:18–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

16
17@Controller('hero')
18export class HeroController implements OnModuleInit {
19 private readonly items: Hero[] = [
20 { id: 1, name: 'John' },
21 { id: 2, name: 'Doe' },
22 ];
23 private heroesService: HeroesService;
24
25 constructor(@Inject('HERO_PACKAGE') private readonly client: ClientGrpc) {}
26
27 onModuleInit() {
28 this.heroesService = this.client.getService<HeroesService>('HeroesService');
29 }
30
31 @Get()
32 getMany(): Observable<Hero[]> {
33 const ids$ = new ReplaySubject<HeroById>();
34 ids$.next({ id: 1 });
35 ids$.next({ id: 2 });
36 ids$.complete();
37
38 const stream = this.heroesService.findMany(ids$.asObservable());
39 return stream.pipe(toArray());
40 }
41
42 @Get(':id')
43 getById(@Param('id') id: string): Observable<Hero> {
44 return this.heroesService.findOne({ id: +id });
45 }
46
47 @GrpcMethod('HeroesService')
48 findOne(data: HeroById): Hero {
49 return this.items.find(({ id }) => id === data.id);
50 }
51
52 @GrpcStreamMethod('HeroesService')
53 findMany(data$: Observable<HeroById>): Observable<Hero> {
54 const hero$ = new Subject<Hero>();
55
56 const onNext = (heroById: HeroById) => {
57 const item = this.items.find(({ id }) => id === heroById.id);
58 hero$.next(item);
59 };
60 const onComplete = () => hero$.complete();
61 data$.subscribe({
62 next: onNext,
63 complete: onComplete,
64 });
65
66 return hero$.asObservable();
67 }
68}

Callers

nothing calls this directly

Calls 2

GrpcMethodFunction · 0.90
GrpcStreamMethodFunction · 0.90

Tested by

no test coverage detected