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

feat(spec): allow defining custom media type of responses + fix(koa): dont overwrite content-type of response #1129

Merged
merged 3 commits into from
Nov 15, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ node_modules
routes.ts
customRoutes.ts
.idea/
*.swp
yarn-error.log
tsconfig.tsbuildinfo
18 changes: 18 additions & 0 deletions packages/cli/src/metadataGeneration/controllerGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ export class ControllerGenerator {
private readonly security?: Tsoa.Security[];
private readonly isHidden?: boolean;
private readonly commonResponses: Tsoa.Response[];
private readonly produces?: string;

constructor(private readonly node: ts.ClassDeclaration, private readonly current: MetadataGenerator) {
this.path = this.getPath();
this.tags = this.getTags();
this.security = this.getSecurity();
this.isHidden = this.getIsHidden();
this.commonResponses = this.getCommonResponses();
this.produces = this.getProduces();
}

public IsValid() {
Expand All @@ -41,6 +43,7 @@ export class ControllerGenerator {
methods: this.buildMethods(),
name: this.node.name.text,
path: this.path || '',
produces: this.produces,
};
}

Expand Down Expand Up @@ -132,4 +135,19 @@ export class ControllerGenerator {

return true;
}

private getProduces(): string | undefined {
const producesDecorators = getDecorators(this.node, identifier => identifier.text === 'Produces');

if (!producesDecorators || !producesDecorators.length) {
return;
}
if (producesDecorators.length > 1) {
throw new GenerateMetadataError(`Only one Produces decorator allowed in '${this.node.name!.text}' class.`);
}

const [decorator] = producesDecorators;
const [produces] = getDecoratorValues(decorator, this.current.typeChecker);
return produces;
}
}
25 changes: 23 additions & 2 deletions packages/cli/src/metadataGeneration/methodGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { getHeaderType } from '../utils/headerTypeHelpers';
export class MethodGenerator {
private method: 'options' | 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head';
private path: string;
private produces?: string;

constructor(
private readonly node: ts.MethodDeclaration,
Expand Down Expand Up @@ -62,6 +63,7 @@ export class MethodGenerator {
operationId: this.getOperationId(),
parameters,
path: this.path,
produces: this.produces,
responses,
successStatus: successStatus,
security: this.getSecurity(),
Expand Down Expand Up @@ -134,6 +136,22 @@ export class MethodGenerator {
// todo: what if someone has multiple no argument methods of the same type in a single controller?
// we need to throw an error there
this.path = getPath(decorator, this.current.typeChecker);
this.produces = this.getProduces();
}

private getProduces(): string | undefined {
const producesDecorators = this.getDecoratorsByIdentifier(this.node, 'Produces');

if (!producesDecorators || !producesDecorators.length) {
return;
}
if (producesDecorators.length > 1) {
throw new GenerateMetadataError(`Only one Produces decorator in '${this.getCurrentLocation()}' method, Found: ${producesDecorators.map(d => d.text).join(', ')}`);
}

const [decorator] = producesDecorators;
const [produces] = getDecoratorValues(decorator, this.current.typeChecker);
return produces;
}

private getMethodResponses(): Tsoa.Response[] {
Expand All @@ -145,12 +163,13 @@ export class MethodGenerator {
return decorators.map(decorator => {
const expression = decorator.parent as ts.CallExpression;

const [name, description, example] = getDecoratorValues(decorator, this.current.typeChecker);
const [name, description, example, produces] = getDecoratorValues(decorator, this.current.typeChecker);

return {
description: description || '',
examples: example === undefined ? undefined : [example],
name: name || '200',
produces,
schema: expression.typeArguments && expression.typeArguments.length > 0 ? new TypeResolver(expression.typeArguments[0], this.current).resolve() : undefined,
headers: getHeaderType(expression.typeArguments, 1, this.current),
} as Tsoa.Response;
Expand All @@ -167,6 +186,7 @@ export class MethodGenerator {
description: isVoidType(type) ? 'No content' : description,
examples: this.getMethodSuccessExamples(),
name: isVoidType(type) ? '204' : '200',
produces: this.produces,
schema: type,
},
};
Expand All @@ -175,7 +195,7 @@ export class MethodGenerator {
throw new GenerateMetadataError(`Only one SuccessResponse decorator allowed in '${this.getCurrentLocation()}' method.`);
}

const [name, description] = getDecoratorValues(decorators[0], this.current.typeChecker);
const [name, description, produces] = getDecoratorValues(decorators[0], this.current.typeChecker);
const examples = this.getMethodSuccessExamples();

const expression = decorators[0].parent as ts.CallExpression;
Expand All @@ -186,6 +206,7 @@ export class MethodGenerator {
description: description || '',
examples,
name: name || '200',
produces,
schema: type,
headers,
},
Expand Down
16 changes: 15 additions & 1 deletion packages/cli/src/metadataGeneration/parameterGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ export class ParameterGenerator {
return (tsType.getFlags() & ts.TypeFlags.NumberLiteral) !== 0;
};

const headers = getHeaderType(typeNode.typeArguments, 2, this.current);

return statusArgumentTypes.map(statusArgumentType => {
if (!isNumberLiteralType(statusArgumentType)) {
throw new GenerateMetadataError('@Res() requires the type to be TsoaResponse<HTTPStatusCode, ResBody>', parameter);
Expand All @@ -99,19 +101,31 @@ export class ParameterGenerator {
description: this.getParameterDescription(parameter) || '',
in: 'res',
name: status,
produces: headers ? this.getProducesFromResHeaders(headers) : undefined,
parameterName,
examples,
required: true,
type,
exampleLabels,
schema: type,
validators: {},
headers: getHeaderType(typeNode.typeArguments, 2, this.current),
headers,
deprecated: this.getParameterDeprecation(parameter),
};
});
}

private getProducesFromResHeaders(headers: Tsoa.HeaderType): string | undefined {
const { properties } = headers;
const [contentTypeProp] = (properties || []).filter(p => p.name.toLowerCase() === 'content-type' && p.type.dataType === 'enum');
if (contentTypeProp) {
const type = contentTypeProp.type as Tsoa.EnumType;
const [produces] = type.enums as string[];
return produces;
}
return;
}

private getBodyPropParameter(parameter: ts.ParameterDeclaration): Tsoa.Parameter {
const parameterName = (parameter.name as ts.Identifier).text;
const type = this.getValidatedType(parameter);
Expand Down
3 changes: 1 addition & 2 deletions packages/cli/src/routeGeneration/templates/koa.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,6 @@ export function RegisterRoutes(router: KoaRouter) {

function returnHandler(context: any, next: () => any, statusCode?: number, data?: any, headers: any={}) {
if (!context.headerSent && !context.response.__tsoaResponded) {
context.set(headers);

if (data !== null && data !== undefined) {
context.body = data;
context.status = 200;
Expand All @@ -217,6 +215,7 @@ export function RegisterRoutes(router: KoaRouter) {
context.status = statusCode;
}

context.set(headers);
context.response.__tsoaResponded = true;
return next();
}
Expand Down
25 changes: 16 additions & 9 deletions packages/cli/src/swagger/specGenerator2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ExtendedSpecConfig } from '../cli';
import { Tsoa, assertNever, Swagger } from '@tsoa/runtime';
import { isVoidType } from '../utils/isVoidType';
import { convertColonPathParams, normalisePath } from './../utils/pathUtils';
import { getValue } from './../utils/swaggerUtils';
import { DEFAULT_REQUEST_MEDIA_TYPE, DEFAULT_RESPONSE_MEDIA_TYPE, getValue } from './../utils/swaggerUtils';
import { SpecGenerator } from './specGenerator';
import { UnspecifiedObject } from '../utils/unspecifiedObject';

Expand All @@ -14,13 +14,13 @@ export class SpecGenerator2 extends SpecGenerator {
public GetSpec() {
let spec: Swagger.Spec2 = {
basePath: normalisePath(this.config.basePath as string, '/', undefined, false),
consumes: ['application/json'],
consumes: [DEFAULT_REQUEST_MEDIA_TYPE],
definitions: this.buildDefinitions(),
info: {
title: '',
},
paths: this.buildPaths(),
produces: ['application/json'],
produces: [DEFAULT_RESPONSE_MEDIA_TYPE],
swagger: '2.0',
};

Expand Down Expand Up @@ -146,15 +146,15 @@ export class SpecGenerator2 extends SpecGenerator {
let path = normalisePath(`${normalisedControllerPath}${normalisedMethodPath}`, '/', '', false);
path = convertColonPathParams(path);
paths[path] = paths[path] || {};
this.buildMethod(controller.name, method, paths[path]);
this.buildMethod(controller.name, method, paths[path], controller.produces);
});
});

return paths;
}

private buildMethod(controllerName: string, method: Tsoa.Method, pathObject: any) {
const pathMethod: Swagger.Operation = (pathObject[method.method] = this.buildOperation(controllerName, method));
private buildMethod(controllerName: string, method: Tsoa.Method, pathObject: any, defaultProduces?: string) {
const pathMethod: Swagger.Operation = (pathObject[method.method] = this.buildOperation(controllerName, method, defaultProduces));
pathMethod.description = method.description;
pathMethod.summary = method.summary;
pathMethod.tags = method.tags;
Expand Down Expand Up @@ -187,21 +187,23 @@ export class SpecGenerator2 extends SpecGenerator {
method.extensions.forEach(ext => (pathMethod[ext.key] = ext.value));
}

protected buildOperation(controllerName: string, method: Tsoa.Method): Swagger.Operation {
protected buildOperation(controllerName: string, method: Tsoa.Method, defaultProduces?: string): Swagger.Operation {
const swaggerResponses: { [name: string]: Swagger.Response } = {};

let produces: Array<string | undefined> = [];
method.responses.forEach((res: Tsoa.Response) => {
swaggerResponses[res.name] = {
description: res.description,
};
if (res.schema && !isVoidType(res.schema)) {
produces.push(res.produces);
swaggerResponses[res.name].schema = this.getSwaggerType(res.schema) as Swagger.Schema;
}
if (res.examples && res.examples[0]) {
if ((res.exampleLabels?.filter(e => e).length || 0) > 0) {
console.warn('Example labels are not supported in OpenAPI 2');
}
swaggerResponses[res.name].examples = { 'application/json': res.examples[0] } as Swagger.Example;
swaggerResponses[res.name].examples = { [DEFAULT_RESPONSE_MEDIA_TYPE]: res.examples[0] } as Swagger.Example;
}

if (res.headers) {
Expand All @@ -220,9 +222,14 @@ export class SpecGenerator2 extends SpecGenerator {
}
});

produces = Array.from(new Set(produces.filter(p => p)));
mrl5 marked this conversation as resolved.
Show resolved Hide resolved
if (produces.length === 0) {
produces = [defaultProduces || DEFAULT_RESPONSE_MEDIA_TYPE];
}

const operation: Swagger.Operation = {
operationId: this.getOperationId(method.name),
produces: ['application/json'],
produces: produces as string[],
responses: swaggerResponses,
};

Expand Down
17 changes: 9 additions & 8 deletions packages/cli/src/swagger/specGenerator3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ExtendedSpecConfig } from '../cli';
import { Tsoa, assertNever, Swagger } from '@tsoa/runtime';
import { isVoidType } from '../utils/isVoidType';
import { convertColonPathParams, normalisePath } from './../utils/pathUtils';
import { getValue } from './../utils/swaggerUtils';
import { DEFAULT_REQUEST_MEDIA_TYPE, DEFAULT_RESPONSE_MEDIA_TYPE, getValue } from './../utils/swaggerUtils';
import { SpecGenerator } from './specGenerator';
import { UnspecifiedObject } from '../utils/unspecifiedObject';

Expand Down Expand Up @@ -239,15 +239,15 @@ export class SpecGenerator3 extends SpecGenerator {
let path = normalisePath(`${normalisedControllerPath}${normalisedMethodPath}`, '/', '', false);
path = convertColonPathParams(path);
paths[path] = paths[path] || {};
this.buildMethod(controller.name, method, paths[path]);
this.buildMethod(controller.name, method, paths[path], controller.produces);
});
});

return paths;
}

private buildMethod(controllerName: string, method: Tsoa.Method, pathObject: any) {
const pathMethod: Swagger.Operation3 = (pathObject[method.method] = this.buildOperation(controllerName, method));
private buildMethod(controllerName: string, method: Tsoa.Method, pathObject: any, defaultProduces?: string) {
const pathMethod: Swagger.Operation3 = (pathObject[method.method] = this.buildOperation(controllerName, method, defaultProduces));
pathMethod.description = method.description;
pathMethod.summary = method.summary;
pathMethod.tags = method.tags;
Expand Down Expand Up @@ -289,7 +289,7 @@ export class SpecGenerator3 extends SpecGenerator {
method.extensions.forEach(ext => (pathMethod[ext.key] = ext.value));
}

protected buildOperation(controllerName: string, method: Tsoa.Method): Swagger.Operation3 {
protected buildOperation(controllerName: string, method: Tsoa.Method, defaultProduces?: string): Swagger.Operation3 {
const swaggerResponses: { [name: string]: Swagger.Response3 } = {};

method.responses.forEach((res: Tsoa.Response) => {
Expand All @@ -298,8 +298,9 @@ export class SpecGenerator3 extends SpecGenerator {
};

if (res.schema && !isVoidType(res.schema)) {
const produces = res.produces || defaultProduces || DEFAULT_RESPONSE_MEDIA_TYPE;
swaggerResponses[res.name].content = {
'application/json': {
[produces]: {
schema: this.getSwaggerType(res.schema),
} as Swagger.Schema3,
};
Expand All @@ -311,7 +312,7 @@ export class SpecGenerator3 extends SpecGenerator {
return { ...acc, [exampleLabel === undefined ? `Example ${exampleCounter++}` : exampleLabel]: { value: ex } };
}, {});
/* eslint-disable @typescript-eslint/dot-notation */
(swaggerResponses[res.name].content || {})['application/json']['examples'] = examples;
(swaggerResponses[res.name].content || {})[DEFAULT_RESPONSE_MEDIA_TYPE]['examples'] = examples;
}
}

Expand Down Expand Up @@ -379,7 +380,7 @@ export class SpecGenerator3 extends SpecGenerator {
description: parameter.description,
required: parameter.required,
content: {
'application/json': mediaType,
[DEFAULT_REQUEST_MEDIA_TYPE]: mediaType,
},
};

Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/utils/swaggerUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export const DEFAULT_REQUEST_MEDIA_TYPE = 'application/json';
export const DEFAULT_RESPONSE_MEDIA_TYPE = 'application/json';

export function getValue(type: 'string' | 'number' | 'integer' | 'boolean', member: any) {
if (member === null) {
return null;
Expand Down
15 changes: 14 additions & 1 deletion packages/runtime/src/decorators/response.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IsValidHeader } from '../utils/isHeaderType';
import { HttpStatusCodeLiteral, HttpStatusCodeStringLiteral, OtherValidOpenApiHttpStatusCode } from '../interfaces/response';

export function SuccessResponse<HeaderType extends IsValidHeader<HeaderType> = {}>(name: string | number, description?: string): Function {
export function SuccessResponse<HeaderType extends IsValidHeader<HeaderType> = {}>(name: string | number, description?: string, produces?: string): Function {
return () => {
return;
};
Expand All @@ -11,6 +11,7 @@ export function Response<ExampleType, HeaderType extends IsValidHeader<HeaderTyp
name: HttpStatusCodeLiteral | HttpStatusCodeStringLiteral | OtherValidOpenApiHttpStatusCode,
description?: string,
example?: ExampleType,
produces?: string,
): Function {
return () => {
return;
Expand All @@ -27,3 +28,15 @@ export function Res(): Function {
return;
};
}

/**
* Overrides the default media type of response.
* Can be used on controller level or only for specific method
*
* @link https://swagger.io/docs/specification/media-types/
*/
export function Produces(value: string): Function {
return () => {
return;
};
}
Loading