|
| 1 | +import {DocCollection, Processor} from 'dgeni'; |
| 2 | +import {ApiDoc} from 'dgeni-packages/typescript/api-doc-types/ApiDoc'; |
| 3 | +import {FunctionExportDoc} from 'dgeni-packages/typescript/api-doc-types/FunctionExportDoc'; |
| 4 | +import {MethodMemberDoc} from 'dgeni-packages/typescript/api-doc-types/MethodMemberDoc'; |
| 5 | +import * as ts from 'typescript'; |
| 6 | + |
| 7 | +/** Type describing a function-like API doc (i.e. a function, or a class method member). */ |
| 8 | +type FunctionLikeDoc = (FunctionExportDoc|MethodMemberDoc) & {returns?: {description: string}}; |
| 9 | + |
| 10 | +/** |
| 11 | + * Processor that automatically sets the @return description for |
| 12 | + * asynchronous methods which do not return any value. |
| 13 | + */ |
| 14 | +export class AsyncReturnDescriptionProcessor implements Processor { |
| 15 | + name = 'async-return-description'; |
| 16 | + $runBefore = ['categorizer']; |
| 17 | + |
| 18 | + $process(docs: DocCollection) { |
| 19 | + docs.forEach((doc: ApiDoc) => { |
| 20 | + if (!isFunctionLikeDoc(doc)) { |
| 21 | + return; |
| 22 | + } |
| 23 | + const typeString = getTypeOfFunctionLikeDoc(doc); |
| 24 | + if (!doc.returns && typeString === 'Promise<void>') { |
| 25 | + doc.returns = {description: 'Promise that resolves when the action completes.'}; |
| 26 | + } |
| 27 | + }); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Gets the type of the function-like doc. If no explicit type has been specified, |
| 33 | + * the type checker is used to compute a type string based on the function body. |
| 34 | + */ |
| 35 | +function getTypeOfFunctionLikeDoc(doc: FunctionLikeDoc): string|null { |
| 36 | + if (doc.type) { |
| 37 | + return doc.type; |
| 38 | + } |
| 39 | + |
| 40 | + const decl = doc.declaration as ts.MethodDeclaration|ts.FunctionDeclaration; |
| 41 | + const signature = doc.typeChecker.getSignatureFromDeclaration(decl); |
| 42 | + |
| 43 | + if (!signature) { |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + const returnType = doc.typeChecker.getReturnTypeOfSignature(signature); |
| 48 | + return doc.typeChecker.typeToString(returnType); |
| 49 | +} |
| 50 | + |
| 51 | +/** Whether the given API doc is a function-like doc. */ |
| 52 | +function isFunctionLikeDoc(doc: ApiDoc): doc is FunctionLikeDoc { |
| 53 | + return doc instanceof FunctionExportDoc || doc instanceof MethodMemberDoc; |
| 54 | +} |
0 commit comments