简体   繁体   English

如何使用 NestJS 创建带参数的嵌套路由

[英]How to create nested routes with parameters using NestJS

I need to build an API where most of the routes are prefixed with a common URL part which also has a parameter.我需要构建一个 API,其中大多数路由都以一个公共 URL 部分为前缀,该部分也有一个参数。

In my specific case, my routes need to look like:在我的具体情况下,我的路线需要如下所示:

/accounts/:account/resource1/:someParam

/accounts/:account/resource2/:someParam/whatever

/accounts/:account/resource3/

/accounts/:account/resource4/subResource/

and so on..等等..

So ideally I would create a parent route /accounts/:account/ which will contain the children routes ( resource1 , resource2 , resource3 , resource4 , etc...).所以理想情况下,我会创建一个路由/accounts/:account/ ,它将包含路由( resource1resource2resource3resource4等...)。

I also need the :account parameter to be accessible from all the children routes.我还需要可以从所有子路由访问:account参数。

What is the best way to achieve this with NestJS ?使用 NestJS 实现这一目标的最佳方法是什么?

Regarding your use case, you might want to take a look at this router module关于您的用例,您可能想看看这个路由器模块
=> https://github.com/shekohex/nest-router => https://github.com/shekohex/nest-router

Following the documentation of this module, you can define your routes like so:按照这个模块的文档,你可以像这样定义你的路由:

... //imports
const routes: Routes = [
    {
      path: '/ninja',
      module: NinjaModule,
      children: [
        {
          path: '/cats',
          module: CatsModule,
        },
        {
          path: '/dogs',
          module: DogsModule,
        },
      ],
    },
  ];

@Module({
  imports: [
      RouterModule.forRoutes(routes), // setup the routes
      CatsModule,
      DogsModule,
      NinjaModule
      ], // as usual, nothing new
})
export class ApplicationModule {}

Of course, the routes would be defined in a separate file like routes.ts当然,路由将在一个单独的文件中定义,例如routes.ts

Given the fact you have a controller by module, the previous code would end in the following tree of routes:鉴于您有一个按模块的控制器,前面的代码将在以下路由树中结束:

ninja
    ├── /
    ├── /katana
    ├── cats
    │   ├── /
    │   └── /ketty
    ├── dogs
        ├── /
        └── /puppy

Example : If you want to reach the ketty controller's routes, you will need to reach this endpoint:示例:如果您想访问ketty控制器的路由,您将需要访问此端点:
<your-api-host>/ninja/cats/ketty


Update This approach is outdated today if you using NestJs v8.0.0 or later, as the documentation of nest-router tells us it's now included on @nestjs/core更新如果您使用 NestJs v8.0.0或更高版本,这种方法今天已经过时,因为nest-router的文档告诉我们它现在包含在@nestjs/core

and also as pointed by @yehonatan yehezkel, you can follow the documentation for the recommended approach at here https://docs.nestjs.com/recipes/router-module并且正如@yehonatan yehezkel 所指出的那样,您可以在此处遵循推荐方法的文档https://docs.nestjs.com/recipes/router-module

i think you need this?我想你需要这个?

import {Controller, Get, Param} from "@nestjs/common";

@Controller('accounts/:account')
export class TestController{

    @Get('resource2/:someParam/whatever')
    arsPW(@Param('account') account, @Param('someParam') someparam){
        console.log(':account/resource2/:someParam/whatever',account,someparam)
        return account+'_'+someparam+'___';
    }

    @Get('resource1/:someparam')
    aRSP(@Param('account') account, @Param('someparam') someparam){
        console.log(':account/resource1/:someParam',account,someparam)
        return account+'_'+someparam;
    }


    @Get()
    getget(){
        console.log('get');
        return 'aaa';
    }

}

Parent controller :父控制器:

@Controller('accounts')
export class AccountsController {
  // http://api.domaine.com/accounts
  @Get()

Child controller :儿童控制器:

@Controller('accounts/:id')
export class ResourcesController {
  // http://api.domaine.com/accounts/1/resources
  @Get('resources')

you can simply do this你可以简单地做到这一点

@Controller('trainer/:trainerId/heroes')
 export class HeroesController {
    constructor(private readonly heroesService: HeroesService) {}

    @Get(':id')
    findOne(@Param('trainerId') trainerId:string,@Param('id') id: string) {
       return `This action returns a #${id} hero trainer id ${trainerId}`;
    }

 }

the uri is: uri是:

http://localhost:3000/trainer/4/heroes/5

thr result is结果是

This action returns a #5 hero trainer id 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM