Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Versioning Nestjs routes?

Tags:

nestjs

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.

like image 692
Brandon Avatar asked Dec 18 '17 03:12

Brandon


2 Answers

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.

like image 117
Kamil Myśliwiec Avatar answered Sep 19 '22 15:09

Kamil Myśliwiec


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

like image 23
Shady Khalifa Avatar answered Sep 18 '22 15:09

Shady Khalifa