简体   繁体   English

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

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

I want to add routing prefixes at the module level and/or have complex global routing prefix logic in general.我想在模块级别添加路由前缀和/或通常具有复杂的全局路由前缀逻辑。

I know I can use the undocumented function NestApplication.setGlobalPrefix to set a single global prefix:我知道我可以使用未记录的函数NestApplication.setGlobalPrefix来设置单个全局前缀:

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

However, I want to set prefixes at the module level in this case.但是,在这种情况下,我想在模块级别设置前缀。

It appears I could achieve this by setting my desired prefix into the decorators at the controller level:看来我可以通过在控制器级别的装饰器中设置我想要的前缀来实现这一点:

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

  // TODO: implement
  return {};
}

But this seems fairly hacky and error-prone.但这似乎相当笨拙且容易出错。 Surely there is a better way?当然有更好的方法吗?

Update 2021 2021 年更新

NestJS now supports the original answer natively . NestJS 现在原生支持原始答案

In addtion, NestJS v8 also adds more sophisticated routing when the primary function is versioning an API:此外,当主要功能是对 API 进行版本控制时,NestJS v8 还添加了更复杂的路由

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

Original Answer原答案

The most robust way to accomplish this in NestJS is to use the nest-router package to create a routing tree .在 NestJS 中实现这一点最可靠的方法是使用nest-router包来创建路由树

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

Create a file next to main.ts called routes.ts like so: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,
  },
];

Then, inside your app.module.ts file, add the router before any other modules are loaded:然后,在app.module.ts文件中,加载任何其他模块之前添加路由器:

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

})

Now when you navigate to YourModule controller, all of its routes will be prefixed with eg v1 in this case:现在,当您导航到YourModule控制器时,它的所有路由都将以例如v1为前缀,在这种情况下:

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

Using this approach gives you the most flexibility as each module does not need to know how it will be prefixed;使用这种方法为您提供了最大的灵活性,因为每个模块不需要知道它将如何添加前缀; the application can decide at a higher level.应用程序可以在更高级别做出决定。 Almost more advanced prefixes can be computed dynamic versus relying on a static string.与依赖静态字符串相比,几乎更高级的前缀可以动态计算。

For me, adding a third party package just to achieve this would be a bit unnecessary, let alone the risk of it being outdated/unmaintained.对我来说,添加第三方包只是为了实现这一点是没有必要的,更不用说它过时/未维护的风险了。 You can add your custom route prefix in the Controller class instead.您可以改为在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 {};
     }
  }

Then just simply add this controller inside your Module然后只需将此控制器添加到您的Module

You can now use either the RouterModule configuration or you can exclude some paths from the global prefix configuration (or mix both):您现在可以使用 RouterModule 配置,也可以从全局前缀配置中排除一些路径(或混合使用):

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

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

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

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