In NestJS, creating nested routes with parameters involves several key steps, primarily defining route decorators within controllers. Here is an example of the steps to implement nested routes with parameters:
- Define Parent Module Route: First, create the parent module's controller and use the
@Controllerdecorator to define the parent route.
typescriptimport { Controller, Get } from '@nestjs/common'; @Controller('parent') export class ParentController { @Get() getAllParents() { return 'All parent module data'; } }
- Define Child Module Route: Create the child module's controller and define routes within it, using the
@Controllerdecorator to specify the child route path.
typescriptimport { Controller, Get, Param } from '@nestjs/common'; @Controller('children') export class ChildrenController { @Get() getAllChildren() { return 'All child module data'; } @Get(':id') getChildById(@Param('id') id: string) { return `Child module data ${id}`; } }
- Implement Nested Routes: Nest the child module controller within the parent module controller by using a route path prefix to achieve nesting.
typescriptimport { Controller, Get, Param } from '@nestjs/common'; @Controller('parent/:parentId/children') export class ChildrenController { @Get() getChildrenByParent(@Param('parentId') parentId: string) { return `All child module data for parent ${parentId}`; } @Get(':childId') getChildByParent( @Param('parentId') parentId: string, @Param('childId') childId: string ) { return `Child module data ${childId} for parent ${parentId}`; } }
In the above code, we define nested routes under the parent module parent for the child module children, enabling access to specific data via paths like /parent/123/children/456, where 123 is the parent module ID and 456 is the child module ID.
The above steps demonstrate how to create nested routes with parameters in NestJS. Route parameters in controllers are retrieved using the @Param decorator, enabling dynamic and flexible handling of routes. This nested routing design allows organizing API endpoints by resources and relationships, thereby improving code readability and maintainability.