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(introspectComments): Enhanced comment parsing for error response #2835

Merged
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
49 changes: 39 additions & 10 deletions lib/plugin/utils/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,18 @@ export function getDefaultTypeFormatFlags(enclosingNode: Node) {
return formatFlags;
}

export function getMainCommentOfNode(
node: Node,
sourceFile: SourceFile
): string {
export function getDocComment(node: Node): DocComment {
const tsdocParser: TSDocParser = new TSDocParser();
const parserContext: ParserContext = tsdocParser.parseString(
node.getFullText()
);
const docComment: DocComment = parserContext.docComment;
return parserContext.docComment;
}
export function getMainCommentOfNode(
node: Node,
sourceFile: SourceFile
): string {
const docComment = getDocComment(node);
return renderDocNode(docComment.summarySection).trim();
}

Expand All @@ -168,11 +171,7 @@ export function parseCommentDocValue(docValue: string, type: ts.Type) {
}

export function getTsDocTagsOfNode(node: Node, typeChecker: TypeChecker) {
const tsdocParser: TSDocParser = new TSDocParser();
const parserContext: ParserContext = tsdocParser.parseString(
node.getFullText()
);
const docComment: DocComment = parserContext.docComment;
const docComment = getDocComment(node);

const tagDefinitions: {
[key: string]: {
Expand Down Expand Up @@ -228,6 +227,36 @@ export function getTsDocTagsOfNode(node: Node, typeChecker: TypeChecker) {
return tagResults;
}

export function getTsDocErrorsOfNode(node: Node) {
const tsdocParser: TSDocParser = new TSDocParser();
const parserContext: ParserContext = tsdocParser.parseString(
node.getFullText()
);
const docComment: DocComment = parserContext.docComment;

const tagResults = [];
const errorParsingRegex = /{(\d+)} (.*)/;

const introspectTsDocTags = (docComment: DocComment) => {
const blocks = docComment.customBlocks.filter(
(block) => block.blockTag.tagName === '@throws'
);

blocks.forEach((block) => {
try {
const docValue = renderDocNode(block.content).split('\n')[0].trim();
const match = docValue.match(errorParsingRegex);
tagResults.push({
status: match[1],
description: `"${match[2]}"`
});
} catch (err) {}
});
};
introspectTsDocTags(docComment);
return tagResults;
}

export function getDecoratorArguments(decorator: Decorator) {
const callExpression = decorator.expression;
return (callExpression && (callExpression as CallExpression).arguments) || [];
Expand Down
81 changes: 81 additions & 0 deletions lib/plugin/visitors/controller-class.visitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
getDecoratorArguments,
getDecoratorName,
getMainCommentOfNode,
getTsDocErrorsOfNode,
getTsDocTagsOfNode
} from '../utils/ast-utils';
import {
Expand Down Expand Up @@ -139,6 +140,17 @@ export class ControllerClassVisitor extends AbstractFileVisitor {
typeChecker,
metadata
);

const apiResponseDecoratorsArray = this.createApiResponseDecorator(
factory,
compilerNode,
decorators,
options,
sourceFile,
typeChecker,
metadata
);

const removeExistingApiOperationDecorator =
apiOperationDecoratorsArray.length > 0;

Expand All @@ -160,6 +172,7 @@ export class ControllerClassVisitor extends AbstractFileVisitor {
);
const updatedDecorators = [
...apiOperationDecoratorsArray,
...apiResponseDecoratorsArray,
...existingDecorators,
factory.createDecorator(
factory.createCallExpression(
Expand Down Expand Up @@ -302,6 +315,74 @@ export class ControllerClassVisitor extends AbstractFileVisitor {
}
}

createApiResponseDecorator(
factory: ts.NodeFactory,
node: ts.MethodDeclaration,
decorators: readonly ts.Decorator[],
options: PluginOptions,
sourceFile: ts.SourceFile,
typeChecker: ts.TypeChecker,
metadata: ClassMetadata
) {
if (!options.introspectComments) {
return [];
}
const apiResponseDecorator = getDecoratorOrUndefinedByNames(
[ApiResponse.name],
decorators,
factory
);
let apiResponseExistingProps:
| ts.NodeArray<ts.PropertyAssignment>
| undefined = undefined;

if (apiResponseDecorator && !options.readonly) {
const apiResponseExpr = head(getDecoratorArguments(apiResponseDecorator));
if (apiResponseExpr) {
apiResponseExistingProps =
apiResponseExpr.properties as ts.NodeArray<ts.PropertyAssignment>;
}
}

const tags = getTsDocErrorsOfNode(node);
if (!tags.length) {
return [];
}

return tags.map((tag) => {
const properties = [
...(apiResponseExistingProps ?? factory.createNodeArray())
];
properties.push(
factory.createPropertyAssignment(
'status',
factory.createNumericLiteral(tag.status)
)
);
properties.push(
factory.createPropertyAssignment(
'description',
factory.createNumericLiteral(tag.description)
)
);
const objectLiteralExpr = factory.createObjectLiteralExpression(
compact(properties)
);
const methodKey = node.name.getText();
metadata[methodKey] = objectLiteralExpr;

const apiResponseDecoratorArguments: ts.NodeArray<ts.Expression> =
factory.createNodeArray([objectLiteralExpr]);
return factory.createDecorator(
factory.createCallExpression(
factory.createIdentifier(`${OPENAPI_NAMESPACE}.${ApiResponse.name}`),
undefined,
apiResponseDecoratorArguments
)
);
});
}

createDecoratorObjectLiteralExpr(
factory: ts.NodeFactory,
node: ts.MethodDeclaration,
Expand Down
11 changes: 11 additions & 0 deletions test/plugin/fixtures/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export class AppController {
* create a Cat
*
* @remarks Creating a test cat
*
* @throws {500} Something is wrong.
* @throws {400} Bad Request.
* @throws {400} Missing parameters.
*
* @returns {Promise<Cat>}
* @memberof AppController
Expand Down Expand Up @@ -75,6 +79,10 @@ let AppController = exports.AppController = class AppController {
*
* @remarks Creating a test cat
*
* @throws {500} Something is wrong.
* @throws {400} Bad Request.
* @throws {400} Missing parameters.
*
* @returns {Promise<Cat>}
* @memberof AppController
*/
Expand Down Expand Up @@ -109,6 +117,9 @@ let AppController = exports.AppController = class AppController {
};
__decorate([
openapi.ApiOperation({ summary: \"create a Cat\", description: \"Creating a test cat\" }),
openapi.ApiResponse({ status: 500, description: "Something is wrong." }),
openapi.ApiResponse({ status: 400, description: "Bad Request." }),
openapi.ApiResponse({ status: 400, description: "Missing parameters." }),
(0, common_1.Post)(),
openapi.ApiResponse({ status: 201, type: Cat })
], AppController.prototype, \"create\", null);
Expand Down