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

Jef*_*xon 4 javascript node.js express typescript nestjs

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

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

// main.ts
app.setGlobalPrefix(version);
Run Code Online (Sandbox Code Playgroud)

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

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

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

  // TODO: implement
  return {};
}
Run Code Online (Sandbox Code Playgroud)

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

Jef*_*xon 6

2021 年更新

NestJS 现在原生支持原始答案

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

@Controller({
  path: 'cats',
  version: '1', // 
})
export class CatsController {
...
Run Code Online (Sandbox Code Playgroud)

原答案

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

yarn add nest-router
# or npm i nest-router
Run Code Online (Sandbox Code Playgroud)

创建文件旁边main.ts名为routes.ts像这样:

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

export const routes: Routes = [
  {
    path: '/v1',
    module: YourModule,
  },
];
Run Code Online (Sandbox Code Playgroud)

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

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

})
Run Code Online (Sandbox Code Playgroud)

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

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

export const routes: Routes = [
  {
    path: '/v1',
    module: YourModule,
  },
];
Run Code Online (Sandbox Code Playgroud)

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