Skip to content
Advertisement

How to deal with NestJS @Get() decorator?

This block of code works properly. I’m able to access both functions with the URL http://localhost:3000/vehicle/availableVehicles & http://localhost:3000/vehicle/1 accordingly

    @Controller('vehicle')
    export class VehicleController {
        constructor(
            private readonly vehicleService: VehicleService,
            private readonly crudService: CurdService
        ) { }
        tableName: string = 'vehicle';
    
        @Get('availableVehicles')
        async availableVehicles() {
            return await this.vehicleService.availableVehicles();
        }
        
        @Get(':id')
        async getbyId(@Req() request: Request) {
            return await this.crudService.getById(this.tableName, request.params.id);
        }
  }

But when I just swap between the 2 functions like code block below then the function availableVehicles() doesn’t work & the URL http://localhost:3000/vehicle/availableVehicles hits the getbyId() function. What to do? Or what I’m doing wrong? Thanks in advance.

    @Controller('vehicle')
    export class VehicleController {
        constructor(
            private readonly vehicleService: VehicleService,
            private readonly crudService: CurdService
        ) { }
        tableName: string = 'vehicle';

        @Get(':id')
        async getbyId(@Req() request: Request) {
            return await this.crudService.getById(this.tableName, request.params.id);
        }
    
        @Get('availableVehicles')
        async availableVehicles() {
            return await this.vehicleService.availableVehicles();
        }
  }

Advertisement

Answer

You just do exactly what you did in the first example, put the more specific routes above the ones that take route parameters.

When the server’s routing table is being built on application startup they will be discovered and registered in this order.

This is a duplicate of https://stackoverflow.com/a/68727403/1364771

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement