[英]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 {};
}
但這似乎相當笨拙且容易出錯。 當然有更好的方法嗎?
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.