#Custom controller decorator calling a async service method

1 messages · Page 1 of 1 (latest)

unborn holly
#

Hi everybody 👋🏼

Simple question : is there a way to call a async service method inside a custom controller decorator ?

Here's the use case : I have several endpoints which accepts a gameId in query. The logic of retrieving the game object based on its id is quite simple : it's an async call to my mongo database, and throw an exception if it's not found.

In order to make my code cleaner, I would like to create a custom decorator which will manage this little logic and give it to the controller. Here's what I want to achieve :

@Post(":id/play")
  public async makeGamePlay(
    @Param("id", ValidateMongoId) id: string, // <==== I want here to get for example : @Game(id) game: Game 
    @Body() makeGamePlayDto: MakeGamePlayDto,
  ): Promise<Game> {
    try {
      return await this.gameService.makeGamePlay(id, makeGamePlayDto);
    } catch (err) {
      throw getControllerRouteError(err);
    }
  }

In the docs, there's an exemple but it's not async and doesn't call a service method. Are custom decorators the best way to do here ?

Thanks a lot for your great help.

unborn holly
#

Any ideas ?

vague monolith
#

Why not use a pipe?

unborn holly
#

Hello ! The pipe can be async and access to other services methods ?

vague monolith
#

Yep

unborn holly
#

Wonderful ! If I throw an Exception in this Pipe, will it be catch in my Controller function ? As it is called in its parameters

vague monolith
#

It'll go to the exception filter

unborn holly
#

That's right ! Thanks for the clarification. Are pipes awaited by default ?

vague monolith
#

If you make them async, yes

#

This is explained in the docs