5

I have built a nestjs webapi and implemented versioning at controller and action level as per https://docs.nestjs.com/techniques/versioning

The solution i am looking into is, i want to generate 2 different swagger based on the controller version. For example, i have 2 controller defined for 2 different version. if i hit [example.com/v1/swagger] , it should load only v1 version controller swagger doc and similarly for v2

Sathish
  • 159
  • 1
  • 4
  • 18
  • did you check this [issue](https://github.com/nestjs/swagger/issues/1495)? Is it relatable to your problem? – wald3 Feb 10 '22 at 12:38
  • @wald3 : No.. I am looking for Swagger versioning aligned with nestjs versioning – Sathish Feb 11 '22 at 11:34

1 Answers1

3

I recently updated my API to support versioning. I couldn't get the Swagger docs to load correctly. Here is my solution, I hope it helps!

Before, we had used app.setGlobalPrefix(APP_ROUTE_PREFIX) to define the prefix.

const APP_ROUTE_PREFIX = 'api/v2';
app.setGlobalPrefix(APP_ROUTE_PREFIX);

Swagger docs were mounted as:

SwaggerModule.setup(`${APP_ROUTE_PREFIX}/docs`, app, document);

To adopt versioning, the following was changed.

  1. Route prefix no longer includes the version; let Nestjs handle it.
const APP_ROUTE_PREFIX = 'api';
  1. Versioning is enabled, with a default of '2', mimicking previous behavior.
  app
    .enableVersioning({ type: VersioningType.URI, defaultVersion: '2' })
    .setGlobalPrefix(APP_ROUTE_PREFIX);
  1. To get Swagger docs to mount correctly, we had to use a variable :version in the path.
  SwaggerModule.setup(`${APP_ROUTE_PREFIX}/:version/docs`, app, document);
  1. Next, we changed on a per-controller basis the controllers that need to adopt versioning.
@Controller({ path: 'objects/:id', version: ['2', '3'] })
  1. Finally, we changed on a per-route basis the handlers that support multiple versions.
  @Version('2')
  getPageV2(): Promise<Observable<unknown>> {
    return this.service.getOkayData();
  }

  @Version('3')
  getPageV3(): Promise<Observable<unknown>> {
    return this.service.getBetterData();
  }