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

auto generate description from comments #585

Merged
merged 5 commits into from
Aug 20, 2020
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
/.idea
/.awcache
/.vscode
.history

# misc
npm-debug.log
Expand Down
2 changes: 1 addition & 1 deletion lib/plugin/compiler-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const before = (options?: Record<string, any>, program?: ts.Program) => {
return modelClassVisitor.visit(sf, ctx, program, options);
}
if (isFilenameMatched(options.controllerFileNameSuffix, sf.fileName)) {
return controllerClassVisitor.visit(sf, ctx, program);
return controllerClassVisitor.visit(sf, ctx, program, options);
}
return sf;
};
Expand Down
6 changes: 5 additions & 1 deletion lib/plugin/merge-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ export interface PluginOptions {
dtoFileNameSuffix?: string | string[];
controllerFileNameSuffix?: string | string[];
classValidatorShim?: boolean;
dtoKeyOfComment?: string;
controllerKeyOfComment?: string;
}

const defaultOptions: PluginOptions = {
dtoFileNameSuffix: ['.dto.ts', '.entity.ts'],
controllerFileNameSuffix: ['.controller.ts'],
classValidatorShim: true
classValidatorShim: true,
dtoKeyOfComment: 'description',
controllerKeyOfComment: 'description'
};

export const mergePluginOptions = (
Expand Down
47 changes: 46 additions & 1 deletion lib/plugin/utils/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import {
Type,
TypeChecker,
TypeFlags,
TypeFormatFlags
TypeFormatFlags,
SourceFile,
getTrailingCommentRanges,
getLeadingCommentRanges,
CommentRange
} from 'typescript';
import { isDynamicallyAdded } from './plugin-utils';

Expand Down Expand Up @@ -98,6 +102,47 @@ export function getDefaultTypeFormatFlags(enclosingNode: Node) {
return formatFlags;
}

export function getMainCommentAndExamplesOfNode(
node: Node,
sourceFile: SourceFile,
needExamples?: boolean
): [string, string[]] {
const sourceText = sourceFile.getFullText();

const replaceRegex = /^ *\** *@.*$|^ *\/\*+ *|^ *\/\/+.*|^ *\/+ *|^ *\*+ *| +$| *\**\/ *$/gim;

const commentResult = [];
const examplesResult = [];
const extractCommentsAndExamples = (comments?: CommentRange[]) =>
comments?.forEach(comment => {
const commentSource = sourceText.substring(comment.pos, comment.end);
const oneComment = commentSource.replace(replaceRegex, '').trim();
if (oneComment) {
commentResult.push(oneComment);
}
if (needExamples) {
const regexOfExample = /@example *['"]?([^ ]+?)['"]? *$/gim;
let execResult: RegExpExecArray;
while (
(execResult = regexOfExample.exec(commentSource)) &&
execResult.length > 1
) {
examplesResult.push(execResult[1]);
}
}
});
extractCommentsAndExamples(
getLeadingCommentRanges(sourceText, node.getFullStart())
);
if (!commentResult.length) {
extractCommentsAndExamples(
getTrailingCommentRanges(sourceText, node.getFullStart())
);
}

return [commentResult.join('\n'), examplesResult];
}

export function getDecoratorArguments(decorator: Decorator) {
const callExpression = decorator.expression;
return (callExpression && (callExpression as CallExpression).arguments) || [];
Expand Down
88 changes: 78 additions & 10 deletions lib/plugin/visitors/controller-class.visitor.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
import { compact, head } from 'lodash';
import * as ts from 'typescript';
import { ApiResponse } from '../../decorators';
import { ApiResponse, ApiOperation } from '../../decorators';
import { OPENAPI_NAMESPACE } from '../plugin-constants';
import { getDecoratorArguments } from '../utils/ast-utils';
import {
getDecoratorArguments,
getMainCommentAndExamplesOfNode
} from '../utils/ast-utils';
import {
getDecoratorOrUndefinedByNames,
getTypeReferenceAsString,
hasPropertyKey,
replaceImportPath
} from '../utils/plugin-utils';
import { AbstractFileVisitor } from './abstract.visitor';
import { PluginOptions } from '../merge-options';

export class ControllerClassVisitor extends AbstractFileVisitor {
visit(
sourceFile: ts.SourceFile,
ctx: ts.TransformationContext,
program: ts.Program
program: ts.Program,
options: PluginOptions
) {
const typeChecker = program.getTypeChecker();
sourceFile = this.updateImports(sourceFile);

const visitNode = (node: ts.Node): ts.Node => {
if (ts.isMethodDeclaration(node)) {
return this.addDecoratorToNode(node, typeChecker, sourceFile.fileName);
return this.addDecoratorToNode(
node,
typeChecker,
options,
sourceFile.fileName,
sourceFile
);
}
return ts.visitEachChild(node, visitNode, ctx);
};
Expand All @@ -32,17 +43,23 @@ export class ControllerClassVisitor extends AbstractFileVisitor {
addDecoratorToNode(
compilerNode: ts.MethodDeclaration,
typeChecker: ts.TypeChecker,
hostFilename: string
options: PluginOptions,
hostFilename: string,
sourceFile: ts.SourceFile
): ts.MethodDeclaration {
const node = ts.getMutableClone(compilerNode);
if (!node.decorators) {
return compilerNode;
}
const { pos, end } = node.decorators;
const nodeArray = node.decorators || ts.createNodeArray();
const { pos, end } = nodeArray;

node.decorators = Object.assign(
[
...node.decorators,
...this.createApiOperationOrEmptyInArray(
node,
nodeArray,
options,
sourceFile
),
...nodeArray,
ts.createDecorator(
ts.createCall(
ts.createIdentifier(`${OPENAPI_NAMESPACE}.${ApiResponse.name}`),
Expand All @@ -63,6 +80,57 @@ export class ControllerClassVisitor extends AbstractFileVisitor {
return node;
}

createApiOperationOrEmptyInArray(
node: ts.MethodDeclaration,
nodeArray: ts.NodeArray<ts.Decorator>,
options: PluginOptions,
sourceFile: ts.SourceFile
) {
const keyToGenerate = options.controllerKeyOfComment;
const apiOperationDecorator = getDecoratorOrUndefinedByNames(
[ApiOperation.name],
nodeArray
);
let apiOperationOptions: ts.ObjectLiteralExpression;
let apiOperationOptionsProperties: ts.NodeArray<ts.PropertyAssignment>;
let comments;
if (
// No ApiOperation or No ApiOperationOptions or ApiOperationOptions is empty or No description in ApiOperationOptions
(!apiOperationDecorator ||
!(apiOperationOptions = head(
getDecoratorArguments(apiOperationDecorator)
)) ||
!(apiOperationOptionsProperties = apiOperationOptions.properties as ts.NodeArray<
ts.PropertyAssignment
>) ||
!hasPropertyKey(keyToGenerate, apiOperationOptionsProperties)) &&
// Has comments
([comments] = getMainCommentAndExamplesOfNode(node, sourceFile))[0]
) {
const properties = [
ts.createPropertyAssignment(keyToGenerate, ts.createLiteral(comments)),
...(apiOperationOptionsProperties ?? ts.createNodeArray())
];
const apiOperationDecoratorArguments: ts.NodeArray<ts.Expression> = ts.createNodeArray(
[ts.createObjectLiteral(compact(properties))]
);
if (apiOperationDecorator) {
(apiOperationDecorator.expression as ts.CallExpression).arguments = apiOperationDecoratorArguments;
} else {
return [
ts.createDecorator(
ts.createCall(
ts.createIdentifier(`${OPENAPI_NAMESPACE}.${ApiOperation.name}`),
undefined,
apiOperationDecoratorArguments
)
)
];
}
}
return [];
}

createDecoratorObjectLiteralExpr(
node: ts.MethodDeclaration,
typeChecker: ts.TypeChecker,
Expand Down
80 changes: 75 additions & 5 deletions lib/plugin/visitors/model-class.visitor.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { compact, flatten, head } from 'lodash';
import * as ts from 'typescript';
import { ApiHideProperty } from '../../decorators';
import {
ApiHideProperty,
ApiProperty,
ApiPropertyOptional
} from '../../decorators';
import { PluginOptions } from '../merge-options';
import { METADATA_FACTORY_NAME } from '../plugin-constants';
import { getDecoratorArguments, getText, isEnum } from '../utils/ast-utils';
import {
getDecoratorArguments,
getText,
isEnum,
getMainCommentAndExamplesOfNode
} from '../utils/ast-utils';
import {
extractTypeArgumentIfArray,
getDecoratorOrUndefinedByNames,
Expand Down Expand Up @@ -40,6 +49,23 @@ export class ModelClassVisitor extends AbstractFileVisitor {
if (hidePropertyDecorator) {
return node;
}

let apiOperationOptionsProperties: ts.NodeArray<ts.PropertyAssignment>;
const apiPropertyDecorator = getDecoratorOrUndefinedByNames(
[ApiProperty.name, ApiPropertyOptional.name],
decorators
);
if (apiPropertyDecorator) {
apiOperationOptionsProperties = head(
getDecoratorArguments(apiPropertyDecorator)
)?.properties;
node.decorators = ts.createNodeArray([
...node.decorators.filter(
decorator => decorator != apiPropertyDecorator
)
]);
}

const isPropertyStatic = (node.modifiers || []).some(
(modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword
);
Expand All @@ -51,6 +77,7 @@ export class ModelClassVisitor extends AbstractFileVisitor {
node,
typeChecker,
options,
apiOperationOptionsProperties ?? ts.createNodeArray(),
sourceFile.fileName,
sourceFile
);
Expand Down Expand Up @@ -100,15 +127,17 @@ export class ModelClassVisitor extends AbstractFileVisitor {
compilerNode: ts.PropertyDeclaration,
typeChecker: ts.TypeChecker,
options: PluginOptions,
existingProperties: ts.NodeArray<ts.PropertyAssignment>,
hostFilename: string,
sourceFile: ts.SourceFile
) {
const objectLiteralExpr = this.createDecoratorObjectLiteralExpr(
compilerNode,
typeChecker,
ts.createNodeArray(),
existingProperties,
options,
hostFilename
hostFilename,
sourceFile
);
this.addClassMetadata(compilerNode, objectLiteralExpr, sourceFile);
}
Expand All @@ -120,12 +149,52 @@ export class ModelClassVisitor extends AbstractFileVisitor {
ts.PropertyAssignment
> = ts.createNodeArray(),
options: PluginOptions = {},
hostFilename = ''
hostFilename = '',
sourceFile?: ts.SourceFile
): ts.ObjectLiteralExpression {
const isRequired = !node.questionToken;

const descriptionPropertyWapper = [];
const examplesPropertyWapper = [];
if (sourceFile) {
const [comments, examples] = getMainCommentAndExamplesOfNode(
node,
sourceFile,
true
);
const keyOfComment = options?.dtoKeyOfComment ??'description';
if (!hasPropertyKey(keyOfComment, existingProperties) && comments) {
descriptionPropertyWapper.push(
ts.createPropertyAssignment(keyOfComment, ts.createLiteral(comments))
);
}
if (
!(
hasPropertyKey('example', existingProperties) ||
hasPropertyKey('examples', existingProperties)
) &&
examples.length
) {
if (examples.length == 1) {
examplesPropertyWapper.push(
ts.createPropertyAssignment(
'example',
ts.createLiteral(examples[0])
)
);
} else {
examplesPropertyWapper.push(
ts.createPropertyAssignment(
'examples',
ts.createArrayLiteral(examples.map(e => ts.createLiteral(e)))
)
);
}
}
}
let properties = [
...existingProperties,
...descriptionPropertyWapper,
!hasPropertyKey('required', existingProperties) &&
ts.createPropertyAssignment('required', ts.createLiteral(isRequired)),
this.createTypePropertyAssignment(
Expand All @@ -134,6 +203,7 @@ export class ModelClassVisitor extends AbstractFileVisitor {
existingProperties,
hostFilename
),
...examplesPropertyWapper,
this.createDefaultPropertyAssignment(node, existingProperties),
this.createEnumPropertyAssignment(
node,
Expand Down
4 changes: 3 additions & 1 deletion test/plugin/controller-class-visitor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ describe('Controller methods', () => {
const result = ts.transpileModule(appControllerText, {
compilerOptions: options,
fileName: filename,
transformers: { before: [before({}, fakeProgram)] }
transformers: {
before: [before({ controllerKeyOfComment: 'summary' }, fakeProgram)]
}
});
expect(result.outputText).toEqual(appControllerTextTranspiled);
});
Expand Down
Loading