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.
- Route prefix no longer includes the version; let Nestjs handle it.
const APP_ROUTE_PREFIX = 'api';
- Versioning is enabled, with a default of '2', mimicking previous behavior.
app
.enableVersioning({ type: VersioningType.URI, defaultVersion: '2' })
.setGlobalPrefix(APP_ROUTE_PREFIX);
- 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);
- Next, we changed on a per-controller basis the controllers that need to adopt versioning.
@Controller({ path: 'objects/:id', version: ['2', '3'] })
- 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();
}