Skip to content

feat(@ApiExtension): When used on a controller it applies to all methods #3485

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
71 changes: 55 additions & 16 deletions e2e/api-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@
"create cats"
],
"x-foo": {
"test": "bar "
"from-method": "bar"
}
},
"get": {
Expand Down Expand Up @@ -646,6 +646,9 @@
"source": "console.log('Hello World');"
}
],
"x-foo": {
"from-controller": true
},
"x-multiple": {
"test": "test"
}
Expand Down Expand Up @@ -725,7 +728,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/{id}": {
Expand Down Expand Up @@ -806,7 +812,10 @@
"tags": [
"cats"
],
"x-auth-type": "NONE"
"x-auth-type": "NONE",
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/explicit-query": {
Expand Down Expand Up @@ -1025,7 +1034,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/bulk": {
Expand Down Expand Up @@ -1101,7 +1113,10 @@
"summary": "Find all cats in bulk",
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
},
"post": {
"operationId": "CatsController_createBulk",
Expand Down Expand Up @@ -1169,7 +1184,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/as-form-data": {
Expand Down Expand Up @@ -1255,7 +1273,10 @@
"summary": "Create cat",
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/wildcard/{path}": {
Expand Down Expand Up @@ -1312,7 +1333,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/with-enum/{type}": {
Expand Down Expand Up @@ -1382,7 +1406,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/with-enum-named/{type}": {
Expand Down Expand Up @@ -1449,7 +1476,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/with-random-query": {
Expand Down Expand Up @@ -1528,7 +1558,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/download": {
Expand Down Expand Up @@ -1587,7 +1620,10 @@
"summary": "",
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
},
"/api/cats/raw-schema-response": {
Expand Down Expand Up @@ -1676,7 +1712,10 @@
],
"tags": [
"cats"
]
],
"x-foo": {
"from-controller": true
}
}
}
},
Expand Down Expand Up @@ -2076,12 +2115,12 @@
]
}
},
"x-schema-extension-multiple": {
"test": "test"
},
"x-schema-extension": {
"test": "test"
},
"x-schema-extension-multiple": {
"test": "test*2"
},
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The order of these extensions changed but I modified the values to make it clear they aren't affected.

"required": [
"name",
"age",
Expand Down
3 changes: 2 additions & 1 deletion e2e/src/cats/cats.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { CatBreed } from './enums/cat-breed.enum';
description: 'Test',
schema: { default: 'test' }
})
@ApiExtension('x-foo', { 'from-controller': true })
@Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {}
Expand Down Expand Up @@ -74,7 +75,7 @@ export class CatsController {
type: () => Cat
})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@ApiExtension('x-foo', { test: 'bar ' })
@ApiExtension('x-foo', { 'from-method': 'bar' })
async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {
return this.catsService.create(createCatDto);
}
Expand Down
2 changes: 1 addition & 1 deletion e2e/src/cats/classes/cat.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ApiExtension, ApiProperty } from '../../../../lib';
import { LettersEnum } from '../dto/pagination-query.dto';

@ApiExtension('x-schema-extension', { test: 'test' })
@ApiExtension('x-schema-extension-multiple', { test: 'test' })
@ApiExtension('x-schema-extension-multiple', { test: 'test*2' })
export class Cat {
@ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
name: string;
Expand Down
2 changes: 1 addition & 1 deletion e2e/validate-schema.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ describe('Validate OpenAPI schema', () => {
).toEqual('test');
expect(
api.components.schemas['Cat']['x-schema-extension-multiple']['test']
).toEqual('test');
).toEqual('test*2');
expect(
api.paths['/api/cats']['post']['callbacks']['myEvent'][
'{$request.body#/callbackUrl}'
Expand Down
59 changes: 53 additions & 6 deletions lib/decorators/api-extension.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { METHOD_METADATA } from '@nestjs/common/constants';
import { DECORATORS } from '../constants';
import { createMixedDecorator } from './helpers';
import { clone } from 'lodash';
import { clone, merge } from 'lodash';
import { isConstructor } from '@nestjs/common/utils/shared.utils';

function applyExtension(target: any, key: string, value: any): void {
const extensions =
Reflect.getMetadata(DECORATORS.API_EXTENSION, target) || {};
Reflect.defineMetadata(
DECORATORS.API_EXTENSION,
{ [key]: value, ...extensions },
target
);
}

/**
* @publicApi
Expand All @@ -12,9 +23,45 @@ export function ApiExtension(extensionKey: string, extensionProperties: any) {
);
}

const extensionObject = {
[extensionKey]: clone(extensionProperties)
};
return (
target: object | Function,
key?: string | symbol,
descriptor?: TypedPropertyDescriptor<any>
): any => {
const extensionValue = clone(extensionProperties);

// Method-level decorator
if (descriptor) {
applyExtension(descriptor.value, extensionKey, extensionValue);
return descriptor;
}

return createMixedDecorator(DECORATORS.API_EXTENSION, extensionObject);
// Ensure decorator is used on a class
if (typeof target === 'object') {
return target;
}

// Look for API methods
const apiMethods = Object.getOwnPropertyNames(target.prototype)
.filter((propertyKey) => !isConstructor(propertyKey))
.map((propertyKey) =>
Object.getOwnPropertyDescriptor(target.prototype, propertyKey)
)
.filter((methodDescriptor) => methodDescriptor !== undefined)
.filter((methodDescriptor) =>
Reflect.hasMetadata(METHOD_METADATA, methodDescriptor.value)
)
.map((methodDescriptor) => methodDescriptor.value);
Comment on lines +47 to +54
Copy link
Contributor Author

Choose a reason for hiding this comment

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

looking back at this i'm realizing we could consolidate this down a bit.

Suggested change
.map((propertyKey) =>
Object.getOwnPropertyDescriptor(target.prototype, propertyKey)
)
.filter((methodDescriptor) => methodDescriptor !== undefined)
.filter((methodDescriptor) =>
Reflect.hasMetadata(METHOD_METADATA, methodDescriptor.value)
)
.map((methodDescriptor) => methodDescriptor.value);
.map((propertyKey) =>
Object.getOwnPropertyDescriptor(target.prototype, propertyKey)?.value
)
.filter((methodDescriptor) =>
methodDescriptor !== undefined && Reflect.hasMetadata(METHOD_METADATA, methodDescriptor)
);


// If we found API methods, apply the extension, otherwise assume it's a DTO and apply to the class itself.
if (apiMethods.length > 0) {
apiMethods.forEach((method) =>
applyExtension(method, extensionKey, extensionValue)
);
} else {
applyExtension(target, extensionKey, extensionValue);
}

return target;
};
}
Loading