alexDuck
alexDuck

Reputation: 103

How to use parameters in routes with nestjs?

I would like to use 3 routes: ‘project’; ‘project/1’; ‘project/authors’. But when I call ‘project/authors’, triggered ‘project/1’ and I get an error. How to awoid it?

    @Controller('project')
    export class ProjectController {

        @Get()
        async getProjects(@Res() res): Promise<ProjectDto[]> {
            return await this.projectService.getProjects(0, 0).then(projects => res.json(projects));
        }
        @Get(':id')
        async getProject(@Param('id', new ParseIntPipe()) id, @Res() res): Promise<ProjectDto> {
            return await this.projectService.getProjects(id).then(project => res.json(project[0]));
        }

        @Get('/authors')
        async getAuthors(@Res() res): Promise<AuthorDto[]> {
            return await this.projectService.getAuthors().then(authors => res.json(authors));
        }

}

Upvotes: 9

Views: 24945

Answers (2)

Anri
Anri

Reputation: 1693

you should be more specify when you are describing the routes.

In you case Routes can not understand which is route path and which is parameter

you should do :

@Controller('project')
export class ProjectController {

    @Get()
    async getProjects(@Res() res): Promise<ProjectDto[]> {
        return await this.projectService.getProjects(0, 0).then(projects => res.json(projects));
    }
    @Get('/project/:id')
    async getProject(@Param('id', new ParseIntPipe()) id, @Res() res): Promise<ProjectDto> {
        return await this.projectService.getProjects(id).then(project => res.json(project[0]));
    }

    @Get('/authors')
    async getAuthors(@Res() res): Promise<AuthorDto[]> {
        return await this.projectService.getAuthors().then(authors => res.json(authors));
    }

}

when you want to get single item of items use following

@Get('/nameOfItem/:id')

Upvotes: 11

Adrien De Peretti
Adrien De Peretti

Reputation: 3662

In fact in all express app the order of the definitions of all the routes is matter.

In a simple way, it is a first come first serve, the first route matched is the one used to respond your request.

So as much as possible put the static parameters first then the dynamic one.

The only thing that you have to keep in mind is first come first serve :)

Upvotes: 4

Related Questions