Skip to content

Fix/Feat: Support header-based versioning and filtering routes by version #3209

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions e2e/header-version.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { INestApplication, VERSION_NEUTRAL, VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import {
DocumentBuilder,
OpenAPIObject,
SwaggerModule
} from '../lib';
import { ApplicationModule } from './src/dog-app.module';

describe('Validate header-based versioned OpenAPI schema', () => {
let app: INestApplication;
let options: Omit<OpenAPIObject, 'paths'>;

beforeEach(async () => {
app = await NestFactory.create(ApplicationModule, {
logger: false
});
app.setGlobalPrefix('api/');
app.enableVersioning({
type: VersioningType.HEADER,
header: 'x-api-version',
defaultVersion: VERSION_NEUTRAL
});

options = new DocumentBuilder()
.setTitle('Dogs example')
.setDescription('The dogs API description')
.setVersion('1.0')
.setBasePath('api')
.addTag('dogs')
.addBasicAuth()
.addBearerAuth()
.addOAuth2()
.addApiKey()
.addApiKey({ type: 'apiKey' }, 'key1')
.addApiKey({ type: 'apiKey' }, 'key2')
.addCookieAuth()
.addSecurityRequirements('bearer')
.addSecurityRequirements({ basic: [], cookie: [] })
.addGlobalParameters({
name: 'x-tenant-id',
in: 'header',
schema: { type: 'string' }
})
.addGlobalParameters({
name: 'x-api-version',
in: 'header',
schema: { type: 'string' }
})
.build();

await SwaggerModule.loadPluginMetadata(async () => ({
'@nestjs/swagger': {
models: [
[
import('./src/dogs/classes/dog.class'),
{
Dog: {
tags: {
description: 'Tags of the dog',
example: ['tag1', 'tag2'],
required: false
},
siblings: {
required: false,
type: () => ({
ids: { required: true, type: () => Number }
})
}
}
}
],
[
import('./src/dogs/dto/create-dog.dto'),
{
CreateDogDto: {
name: {
description: 'Name of the dog'
}
}
}
]
],
controllers: [
[
import('./src/dogs/dogs.controller'),
{
DogsController: {
findAllBulk: {
type: [
await import('./src/dogs/classes/dog.class').then(
(f) => f.Dog
)
],
summary: 'Find all dogs in bulk'
}
}
}
]
]
}
}));
});

it('should produce a valid OpenAPI 3.0 schema with versions split by modified path', async () => {
const api = SwaggerModule.createDocument(app, options);
console.log(
'API name: %s, Version: %s',
api.info.title,
api.info.version
);
expect(api.info.title).toEqual('Dogs example');

expect(api.paths['/api/dogs']['get']).toBeDefined();

expect(api.paths['/api/dogs version: v0']['post']['operationId']).toBe('DogsController_createNewV0');
expect(
api.paths['/api/dogs version: v0']['post']['responses']['200']['content']['application/json']['schema']['type']
).toBe('array');

expect(api.paths['/api/dogs version: v1']['post']['operationId']).toBe('DogsController_createNewV1');
expect(
api.paths['/api/dogs version: v1']['post']['responses']['200']['content']['application/json']['schema']['type']
).toBe('string');

expect(api.paths['/api/dogs version: v2']['post']['operationId']).toBe('DogsController_createNewV2');
expect(
api.paths['/api/dogs version: v2']['post']['responses']['200']['content']['application/json']['schema']['type']
).toBe('array');
});

it('should support filtering to subset of versions', async () => {
const api = SwaggerModule.createDocument(app, options, { includeVersions: ['v1', 'v2'] });
console.log(
'API name: %s, Version: %s',
api.info.title,
api.info.version
);
expect(api.info.title).toEqual('Dogs example');

expect(api.paths['/api/dogs']['get']).toBeDefined();

expect(api.paths['/api/dogs version: v0']).toBeUndefined();

expect(api.paths['/api/dogs version: v1']['post']['operationId']).toBe('DogsController_createNewV1');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if I'm following. How's this a valid path? (/api/dogs version: v1)

Copy link
Author

@aarongoin aarongoin Feb 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies for the delayed response.

You're correct that it's not a valid path, but there doesn't seem to be any other way of distinguishing between different versioned paths that route via headers when generating OpenAPI spec covering multiple versions simultaneously--something thats possible when versions are specified in the path. Unless perhaps you're suggesting to make it valid path via something like query params or hash route--though that doesn't seem ideal either.

I suppose the only other alternative is to force the user to specify a single API version to generate OpenAPI spec for (with option of including/excluding version-less routes). Do you prefer this alternative? Or do you have some other idea in mind for this?

expect(
api.paths['/api/dogs version: v1']['post']['responses']['200']['content']['application/json']['schema']['type']
).toBe('string');

expect(api.paths['/api/dogs version: v2']['post']['operationId']).toBe('DogsController_createNewV2');
expect(
api.paths['/api/dogs version: v2']['post']['responses']['200']['content']['application/json']['schema']['type']
).toBe('array');
});

it('should support filtering to a single version', async () => {
const api = SwaggerModule.createDocument(app, options, { includeVersions: ['v2'] });
console.log(
'API name: %s, Version: %s',
api.info.title,
api.info.version
);
expect(api.info.title).toEqual('Dogs example');

expect(api.paths['/api/dogs']['get']).toBeDefined();
expect(api.paths['/api/dogs version: v0']).toBeUndefined();
expect(api.paths['/api/dogs version: v1']).toBeUndefined();
expect(api.paths['/api/dogs version: v2']).toBeUndefined();
expect(api.paths['/api/dogs']['post']['operationId']).toBe('DogsController_createNewV2');
expect(
api.paths['/api/dogs']['post']['responses']['200']['content']['application/json']['schema']['type']
).toBe('array');
});
});
9 changes: 9 additions & 0 deletions e2e/src/dog-app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { DogsModule } from './dogs/dogs.module';

@Module({
imports: [DogsModule],
controllers: [AppController]
})
export class ApplicationModule {}
32 changes: 32 additions & 0 deletions e2e/src/dogs/classes/dog.class.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { ApiExtension, ApiProperty } from '../../../../lib';

@ApiExtension('x-schema-extension', { test: 'test' })
@ApiExtension('x-schema-extension-multiple', { test: 'test' })
export class Dog {
@ApiProperty({ example: 'Chonk', description: 'The name of the Dog' })
name: string;

@ApiProperty({ example: 1, minimum: 0, description: 'The age of the Dog' })
age: number;

@ApiProperty({
example: 'Pitt bull',
description: 'The breed of the Dog'
})
breed: string;

@ApiProperty({
name: '_tags',
type: [String]
})
tags?: string[];

@ApiProperty()
createdAt: Date;

@ApiProperty({
type: String,
isArray: true
})
urls?: string[];
}
84 changes: 84 additions & 0 deletions e2e/src/dogs/dogs.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import {
Body,
Controller,
Get,
HttpStatus,
Param,
Post,
Query,
Version,
VERSION_NEUTRAL
} from '@nestjs/common';
import {
ApiBearerAuth,
ApiBody,
ApiCallbacks,
ApiConsumes,
ApiDefaultGetter,
ApiExtension,
ApiHeader,
ApiOperation,
ApiParam,
ApiQuery,
ApiResponse,
ApiSecurity,
ApiTags,
getSchemaPath
} from '../../../lib';
import { DogsService } from './dogs.service';
import { Dog } from './classes/dog.class';
import { CreateDogDto } from './dto/create-dog.dto';

@ApiSecurity('basic')
@ApiBearerAuth()
@ApiSecurity({ key2: [], key1: [] })
@ApiTags('dogs')
@ApiHeader({
name: 'header',
required: false,
description: 'Test',
schema: { default: 'test' }
})
@Controller('dogs')
export class DogsController {
constructor(private readonly dogsService: DogsService) {}

@Get('')
@Version(VERSION_NEUTRAL)
@ApiResponse({
status: 200,
description: 'The list of all dogs',
type: Array<Dog>,
})
getList(): Dog[] {
return this.dogsService.getAll();
}

@Post('')
@Version('0')
@ApiResponse({
status: 200,
description: 'The tail array',
type: Array
})
createNewV0(@Body() dogData: CreateDogDto): Dog { return this.dogsService.create(dogData); }

@Post('')
@Version('1')
@ApiResponse({
status: 200,
description: 'The tail string',
type: String
})
createNewV1(@Body() dogData: CreateDogDto): Dog { return this.dogsService.create(dogData); }

@Post('')
@Version('2')
@ApiResponse({
status: 200,
description: 'The tail array.',
type: Array,
})
createNewV2(@Body() dogData: CreateDogDto): [Dog, boolean] { return [this.dogsService.create(dogData), Math.random() > 0.5]; }

}
9 changes: 9 additions & 0 deletions e2e/src/dogs/dogs.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { DogsController } from './dogs.controller';
import { DogsService } from './dogs.service';

@Module({
controllers: [DogsController],
providers: [DogsService]
})
export class DogsModule {}
17 changes: 17 additions & 0 deletions e2e/src/dogs/dogs.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Injectable } from '@nestjs/common';
import { Dog } from './classes/dog.class';
import { CreateDogDto } from './dto/create-dog.dto';

@Injectable()
export class DogsService {
private readonly dogs: Dog[] = [];

getAll(): Dog[] {
return [...this.dogs];
}

create(dog: CreateDogDto): Dog {
this.dogs.push(dog);
return dog;
}
}
28 changes: 28 additions & 0 deletions e2e/src/dogs/dto/create-dog.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { ApiExtension, ApiProperty } from '../../../../lib';

@ApiExtension('x-tags', ['foo', 'bar'])
export class CreateDogDto {
@ApiProperty()
readonly name: string;

@ApiProperty({ minimum: 1, maximum: 200 })
readonly age: number;

@ApiProperty({ name: '_breed', type: String })
readonly breed: string;

@ApiProperty({
format: 'uri',
type: [String]
})
readonly tags?: string[];

@ApiProperty()
createdAt: Date;

@ApiProperty({
type: 'string',
isArray: true
})
readonly urls?: string[];
}
11 changes: 11 additions & 0 deletions e2e/validate-schema.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,4 +214,15 @@ describe('Validate OpenAPI schema', () => {
}
});
});

it('should support filtering to a single version', async () => {
const api = SwaggerModule.createDocument(app, options, { includeVersions: ['v2'] });
console.log(
'API name: %s, Version: %s',
api.info.title,
api.info.version
);
expect(api.paths['/api/v1/alias1']).toBeUndefined();
expect(api.paths['/api/v2/alias1']).toBeDefined();
});
});
2 changes: 1 addition & 1 deletion lib/decorators/api-callbacks.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DECORATORS } from '../constants';
import { createMixedDecorator } from './helpers';
import { CallBackObject } from '../interfaces/callback-object.interface'
import { CallBackObject } from '../interfaces/callback-object.interface';

export function ApiCallbacks(...callbackObject: Array<CallBackObject<any>>) {
return createMixedDecorator(DECORATORS.API_CALLBACKS, callbackObject);
Expand Down
Loading