Custom param decorator which transform param to database entity

Viewed 739

In Laravel (php) has route /article/:article, and in controller method I get the model:

function getArticle(ArticleModel $article) {...}

How to make this in NestJS? My controller:

@Controller('/articles')
export class ArticlesController {
    @Get('/:article/edit')
    editArticle(@Param('article') articleId: number) {...}
}

How to transform @Param('article') to custom decorator @ArticleParam() which will return my Article entity by id in request?

1 Answers

You can implement a custom pipe that injects a TypeORM repository and returns the database entity when prompted with an ID, something like this:

@Injectable()
export class ArticlePipe implements PipeTransform {
    constructor(@InjectRepository(Article) private repository: Repository<Article>) {}

    transform(value: id, metadata: ArgumentsMetadata): Promise<Article|null> {
        return this.repository.findOneBy({ id });
    }
}

Then use it like

@Get('/article/:id')
getArticle(@Param('id', ArticlePipe) article: Article) { ... }

You just need to make sure to use the pipe only on modules that provide the Article EntityRepository.

Then, if you need the specific @ArticleParam, it should be like this:

export function ArticleParam = () => applyDecorators(
  Param(ArticlePipe)
)
Related