I'm just getting started with Nestjs and am wondering how I can version my API using either a route prefix or through an Express Router instance?
Ideally, I would like to make endpoints accessible via:
/v1
/v2
etc, so I can gracefully degrade endpoints. I'm not seeing where I could add the version prefix. I know it's possible to set a global prefix on the application instance, but that's not for a particular set of endpoints.
Here's an open discussion about the RouterModule
https://github.com/nestjs/nest/issues/255. I understand how important this functionality is, so it should appear in the near future. At this point it is necessary to put v1
/ v2
directly into the @Controller()
decorator.
Router Module comes to rescue, with Nest RouterModule
it's now a painless organizing your routes.
See How it easy to setup.
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 {}
this will produce something like this:
ninja
├── /
├── /katana
├── cats
│ ├── /
│ └── /ketty
├── dogs
├── /
└── /puppy
and sure, for Versioning the routes you could do similar to this
const routes: Routes = [
{
path: '/v1',
children: [CatsModule, DogsModule],
},
{
path: '/v2',
children: [CatsModule2, DogsModule2],
},
];
Nice !
check it out Nest Router
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With