Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use parameters in routes with nestjs?

Tags:

routes

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));
        }

}
like image 725
alexDuck Avatar asked Oct 11 '18 06:10

alexDuck


1 Answers

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')
like image 65
Anri Avatar answered Nov 14 '22 22:11

Anri