繁体   English   中英

如何使用 NestJS 向特定模块添加路由前缀?

[英]How to add a route prefix to specific modules using NestJS?

我想在模块级别添加路由前缀和/或通常具有复杂的全局路由前缀逻辑。

我知道我可以使用未记录的函数NestApplication.setGlobalPrefix来设置单个全局前缀:

// main.ts
app.setGlobalPrefix(version);

但是,在这种情况下,我想在模块级别设置前缀。

看来我可以通过在控制器级别的装饰器中设置我想要的前缀来实现这一点:

//controler.ts
@Get('/PREFIX/health')
async getHealth() {

  // TODO: implement
  return {};
}

但这似乎相当笨拙且容易出错。 当然有更好的方法吗?

2021 年更新

NestJS 现在原生支持原始答案

此外,当主要功能是对 API 进行版本控制时,NestJS v8 还添加了更复杂的路由

@Controller({
  path: 'cats',
  version: '1', // 👈
})
export class CatsController {
...

原答案

在 NestJS 中实现这一点最可靠的方法是使用nest-router包来创建路由树

yarn add nest-router
# or npm i nest-router

main.ts旁边创建一个名为routes.ts的文件, main.ts routes.ts

import { Routes } from 'nest-router';
import { YourModule } from './your/your.module';

export const routes: Routes = [
  {
    path: '/v1',
    module: YourModule,
  },
];

然后,在app.module.ts文件中,加载任何其他模块之前添加路由器:

@Module({
  imports: [
    RouterModule.forRoutes(routes),
    YourModule,
    DebugModule
  ],

})

现在,当您导航到YourModule控制器时,它的所有路由都将以例如v1为前缀,在这种情况下:

curl http://localhost:3000/v1/your/operation

使用这种方法为您提供了最大的灵活性,因为每个模块不需要知道它将如何添加前缀; 应用程序可以在更高级别做出决定。 与依赖静态字符串相比,几乎更高级的前缀可以动态计算。

对我来说,添加第三方包只是为了实现这一点是没有必要的,更不用说它过时/未维护的风险了。 您可以改为在Controller类中添加自定义路由前缀。

  @Controller('custom/prefix')
  export const MyController {

     @Get('health')
     getHealth() {
       //this route would be: custom/prefix/health
       return {};
     }

     @Get('other')
     getOther() {
       //this route would be: custom/prefix/other
       return {};
     }
  }

然后只需将此控制器添加到您的Module

您现在可以使用 RouterModule 配置,也可以从全局前缀配置中排除一些路径(或混合使用):

路由器模块: https ://docs.nestjs.com/recipes/router-module#router-module

全局前缀“排除”: https : //docs.nestjs.com/faq/global-prefix#global-prefix

暂无
暂无

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

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