Skip to content
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

Add decorator to allow specification of the schema type name #983

Closed
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
4 changes: 2 additions & 2 deletions e2e/src/cats/dto/create-cat.dto.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { ApiExtraModels, ApiProperty } from '../../../../lib';
import { ExtraModel } from './extra-model.dto';
import { ExtraModelDto } from './extra-model.dto';
import { LettersEnum } from './pagination-query.dto';
import { TagDto } from './tag.dto';

@ApiExtraModels(ExtraModel)
@ApiExtraModels(ExtraModelDto)
export class CreateCatDto {
@ApiProperty()
readonly name: string;
Expand Down
7 changes: 5 additions & 2 deletions e2e/src/cats/dto/extra-model.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { ApiProperty } from '../../../../lib';
import { ApiProperty, ApiSchema } from '../../../../lib';

export class ExtraModel {
@ApiSchema({
name: 'ExtraModel'
})
export class ExtraModelDto {
@ApiProperty()
readonly one: string;

Expand Down
3 changes: 2 additions & 1 deletion lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ export const DECORATORS = {
API_SECURITY: `${DECORATORS_PREFIX}/apiSecurity`,
API_EXCLUDE_ENDPOINT: `${DECORATORS_PREFIX}/apiExcludeEndpoint`,
API_EXTRA_MODELS: `${DECORATORS_PREFIX}/apiExtraModels`,
API_EXTENSION: `${DECORATORS_PREFIX}/apiExtension`
API_EXTENSION: `${DECORATORS_PREFIX}/apiExtension`,
API_SCHEMA: `${DECORATORS_PREFIX}/apiSchema`
};
20 changes: 20 additions & 0 deletions lib/decorators/api-schema.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { DECORATORS } from '../constants';
import { SchemaObjectMetadata } from '../interfaces/schema-object-metadata.interface';
import { createClassDecorator, createPropertyDecorator } from './helpers';

export interface ApiSchemaOptions extends Pick<SchemaObjectMetadata, 'name'> {
/**
* Name of the schema.
*/
name: string;
}

export function ApiSchema(options: ApiSchemaOptions): ClassDecorator {
return createApiSchemaDecorator(options);
}

export function createApiSchemaDecorator(
options: ApiSchemaOptions
): ClassDecorator {
return createClassDecorator(DECORATORS.API_SCHEMA, [options]);
}
1 change: 1 addition & 0 deletions lib/decorators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ export * from './api-response.decorator';
export * from './api-security.decorator';
export * from './api-use-tags.decorator';
export * from './api-extension.decorator';
export * from './api-schema.decorator';
14 changes: 12 additions & 2 deletions lib/services/schema-object-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
omitBy
} from 'lodash';
import { DECORATORS } from '../constants';
import { ApiSchemaOptions } from '../decorators';
import { getTypeIsArrayTuple } from '../decorators/helpers';
import { exploreGlobalApiExtraModelsMetadata } from '../explorers/api-extra-models.explorer';
import {
Expand Down Expand Up @@ -152,10 +153,19 @@ export class SchemaObjectFactory {
if (typeDefinitionRequiredFields.length > 0) {
typeDefinition['required'] = typeDefinitionRequiredFields;
}
// Find out if user defined custom schema name. If not then use the type name.
const customSchema: ApiSchemaOptions[] = Reflect.getOwnMetadata(
DECORATORS.API_SCHEMA,
type
);
const schemaName =
customSchema && customSchema.length === 1
? customSchema[0].name
: type.name;
schemas.push({
[type.name]: typeDefinition
[schemaName]: typeDefinition
});
return type.name;
return schemaName;
}

mergePropertyWithMetadata(
Expand Down
136 changes: 135 additions & 1 deletion test/explorer/swagger-explorer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
ApiParam,
ApiProduces,
ApiProperty,
ApiQuery
ApiQuery,
ApiSchema
} from '../../lib/decorators';
import { ResponseObject } from '../../lib/interfaces/open-api-spec.interface';
import { ModelPropertiesAccessor } from '../../lib/services/model-properties-accessor';
Expand Down Expand Up @@ -787,4 +788,137 @@ describe('SwaggerExplorer', () => {
]);
});
});
describe('when custom schema names are used', () => {
@ApiSchema({
name: 'Foo'
})
class FooDto {}

@ApiSchema({
name: 'CreateFoo'
})
class CreateFooDto {}

@Controller('')
class FooController {
@Post('foos')
@ApiBody({ type: CreateFooDto })
@ApiOperation({ summary: 'Create foo' })
@ApiCreatedResponse({
type: FooDto,
description: 'Newly created Foo object'
})
create(@Body() createFoo: CreateFooDto): Promise<FooDto> {
return Promise.resolve({});
}

@Get('foos/:objectId')
@ApiParam({ name: 'objectId', type: 'string' })
@ApiQuery({ name: 'page', type: 'string' })
@ApiOperation({ summary: 'List all Foos' })
@ApiOkResponse({ type: [FooDto] })
@ApiDefaultResponse({ type: [FooDto] })
find(
@Param('objectId') objectId: string,
@Query('page') q: string
): Promise<FooDto[]> {
return Promise.resolve([]);
}
}

it('sees two controller operations and their responses', () => {
const explorer = new SwaggerExplorer(schemaObjectFactory);
const routes = explorer.exploreController(
{
instance: new FooController(),
metatype: FooController
} as InstanceWrapper<FooController>,
'path'
);

expect(routes.length).toEqual(2);

// POST
expect(routes[0].root.operationId).toEqual('FooController_create');
expect(routes[0].root.method).toEqual('post');
expect(routes[0].root.path).toEqual('/path/foos');
expect(routes[0].root.summary).toEqual('Create foo');
expect(routes[0].root.parameters.length).toEqual(0);
expect(routes[0].root.requestBody).toEqual({
required: true,
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/CreateFoo'
}
}
}
});

expect(
(routes[0].responses['201'] as ResponseObject).description
).toEqual('Newly created Foo object');
expect(
(routes[0].responses['201'] as ResponseObject).content[
'application/json'
]
).toEqual({
schema: {
$ref: '#/components/schemas/Foo'
}
});

// GET
expect(routes[1].root.operationId).toEqual('FooController_find');
expect(routes[1].root.method).toEqual('get');
expect(routes[1].root.path).toEqual('/path/foos/{objectId}');
expect(routes[1].root.summary).toEqual('List all Foos');
expect(routes[1].root.parameters.length).toEqual(2);
expect(routes[1].root.parameters).toEqual([
{
in: 'path',
name: 'objectId',
required: true,
schema: {
type: 'string'
}
},
{
in: 'query',
name: 'page',
required: true,
schema: {
type: 'string'
}
}
]);
expect(
(routes[1].responses['200'] as ResponseObject).description
).toEqual('');
expect(
(routes[1].responses['200'] as ResponseObject).content[
'application/json'
]
).toEqual({
schema: {
type: 'array',
items: {
$ref: '#/components/schemas/Foo'
}
}
});
expect(
(routes[1].responses.default as ResponseObject).content[
'application/json'
]
).toEqual({
schema: {
type: 'array',
items: {
$ref: '#/components/schemas/Foo'
}
}
});
});
});
});
30 changes: 29 additions & 1 deletion test/services/schema-object-factory.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ApiProperty } from '../../lib/decorators';
import { ApiProperty, ApiSchema } from '../../lib/decorators';
import { ModelPropertiesAccessor } from '../../lib/services/model-properties-accessor';
import { SchemaObjectFactory } from '../../lib/services/schema-object-factory';
import { SwaggerTypesMapper } from '../../lib/services/swagger-types-mapper';
Expand Down Expand Up @@ -235,5 +235,33 @@ describe('SchemaObjectFactory', () => {
properties: { name: { type: 'string', minLength: 1 } }
});
});

it('should use schema name instead of class name', () => {
@ApiSchema({
name: 'CreateUser'
})
class CreateUserDto {}

const schemas = [];

schemaObjectFactory.exploreModelSchema(CreateUserDto, schemas);

expect(Object.keys(schemas[0])[0]).toEqual('CreateUser');
});

it('should not use schema name of base class', () => {
@ApiSchema({
name: 'CreateUser'
})
class CreateUserDto {}

class UpdateUserDto extends CreateUserDto {}

const schemas = [];

schemaObjectFactory.exploreModelSchema(UpdateUserDto, schemas);

expect(Object.keys(schemas[0])[0]).toEqual('UpdateUserDto');
});
});
});