-
Notifications
You must be signed in to change notification settings - Fork 505
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
aarongoin
wants to merge
2
commits into
nestjs:master
Choose a base branch
from
polyapi:2990-header-based-versioning
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
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'); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[]; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; } | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[]; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
)Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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?