All files / metadata methodGenerator.ts

52.32% Statements 79/151
36.96% Branches 34/92
70.59% Functions 24/34
48.8% Lines 61/125
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 2401x   1x 1x 1x 1x   1x       2x 2x     1x 4x     1x 2x 2x   2x 2x 2x 2x   2x                             2x 2x 1x 1x             1x   2x 2x   2x     2x     2x     1x           2x 3x   2x 2x       2x 2x   3x   2x     2x 2x 2x           2x 3x 2x                                                       1x 3x 2x 2x                                                               1x 3x 2x                     1x 9x     1x               1x 3x 2x                 1x 3x 2x                         1x                                                 1x  
import * as ts from 'typescript';
import { Method, ResponseType, Type } from './metadataGenerator';
import { ResolveType } from './resolveType';
import { ParameterGenerator } from './parameterGenerator';
import { getJSDocDescription, getJSDocTag, isExistJSDocTag } from '../utils/jsDocUtils';
import { getDecorators } from '../utils/decoratorUtils';
 
export class MethodGenerator {
    private method: string;
    private path: string;
 
    constructor(private readonly node: ts.MethodDeclaration) {
        this.processMethodDecorators();
    }
 
    public IsValid() {
        return !!this.method;
    }
 
    public Generate(): Method {
        Iif (!this.IsValid()) { throw new Error('This isn\'t a valid a controller method.'); }
        Iif (!this.node.type) { throw new Error('Controller methods must have a return type.'); }
 
        const identifier = this.node.name as ts.Identifier;
        const type = ResolveType(this.node.type);
        const responses = this.getMethodResponses();
        responses.push(this.getMethodSuccessResponse(type));
 
        return {
            deprecated: isExistJSDocTag(this.node, 'deprecated'),
            description: getJSDocDescription(this.node),
            method: this.method,
            name: identifier.text,
            parameters: this.buildParameters(),
            path: this.path,
            responses,
            security: this.getMethodSecurity(),
            summary: getJSDocTag(this.node, 'summary'),
            tags: this.getMethodTags(),
            type
        };
    }
 
    private buildParameters() {
        const parameters = this.node.parameters.map(p => {
            try {
                return new ParameterGenerator(p, this.method, this.path).Generate();
            } catch (e) {
                const methodId = this.node.name as ts.Identifier;
                const controllerId = (this.node.parent as ts.ClassDeclaration).name as ts.Identifier;
                const parameterId = p.name as ts.Identifier;
                throw new Error(`Error generate parameter method: '${controllerId.text}.${methodId.text}' argument: ${parameterId.text} ${e}`);
            }
        }).filter(p => (p.in !== 'context') && (p.in !== 'cookie'));
 
        const bodyParameters = parameters.filter(p => p.in === 'body');
        const formParameters = parameters.filter(p => p.in === 'formData');
 
        Iif (bodyParameters.length > 1) {
            throw new Error(`Only one body parameter allowed in '${this.getCurrentLocation()}' method.`);
        }
        Iif (bodyParameters.length > 0 && formParameters.length > 0) {
            throw new Error(`Choose either during @FormParam and @FileParam or body parameter  in '${this.getCurrentLocation()}' method.`);
        }
        return parameters;
    }
 
    private getCurrentLocation() {
        const methodId = this.node.name as ts.Identifier;
        const controllerId = (this.node.parent as ts.ClassDeclaration).name as ts.Identifier;
        return `${controllerId.text}.${methodId.text}`;
    }
 
    private processMethodDecorators() {
        const httpMethodDecorators = getDecorators(this.node, identifier => this.supportsPathMethod(identifier.text));
 
        Iif (!httpMethodDecorators || !httpMethodDecorators.length) { return; }
        Iif (httpMethodDecorators.length > 1) {
            throw new Error(`Only one HTTP Method decorator in '${this.getCurrentLocation}' method is acceptable, Found: ${httpMethodDecorators.map(d => d.text).join(', ')}`);
        }
 
        const methodDecorator = httpMethodDecorators[0];
        this.method = methodDecorator.text;
 
        const pathDecorators = getDecorators(this.node, identifier => identifier.text === 'Path');
 
        Iif (pathDecorators && pathDecorators.length > 1) {
            throw new Error(`Only one Path decorator in '${this.getCurrentLocation}' method is acceptable, Found: ${httpMethodDecorators.map(d => d.text).join(', ')}`);
        }
        Eif (pathDecorators) {
            const pathDecorator = pathDecorators[0]; // TODO PAthUtils.normalizePath (controlar as / e substituir :id pra {id})
            this.path = pathDecorator ? `/${pathDecorator.arguments[0]}` : '';
        } else {
            this.path = '';
        }
    }
 
    private getMethodResponses(): ResponseType[] {
        const decorators = getDecorators(this.node, identifier => identifier.text === 'Response');
        Eif (!decorators || !decorators.length) { return []; }
 
        return decorators.map(decorator => {
            let description = '';
            let name = '200';
            let examples = undefined;
            if (decorator.arguments.length > 0 && decorator.arguments[0]) {
                name = decorator.arguments[0];
            }
            if (decorator.arguments.length > 1 && decorator.arguments[1]) {
                description = (decorator.arguments[1] as any).text;
            }
            if (decorator.arguments.length > 2 && decorator.arguments[2]) {
                const argument = decorator.arguments[2] as any;
                examples = this.getExamplesValue(argument);
            }
 
            return {
                description: description,
                examples: examples,
                name: name,
                schema: (decorator.typeArguments && decorator.typeArguments.length > 0)
                    ? ResolveType(decorator.typeArguments[0])
                    : undefined
            };
        });
    }
 
    private getMethodSuccessResponse(type: Type): ResponseType {
        const decorators = getDecorators(this.node, identifier => identifier.text === 'SuccessResponse');
        Eif (!decorators || !decorators.length) {
            return {
                description: type.typeName === 'void' ? 'No content' : 'Ok',
                examples: this.getMethodSuccessExamples(),
                name: type.typeName === 'void' ? '204' : '200',
                schema: type
            };
        }
        if (decorators.length > 1) {
            throw new Error(`Only one SuccessResponse decorator allowed in '${this.getCurrentLocation}' method.`);
        }
 
        const decorator = decorators[0];
 
        let description = '';
        let name = '200';
        const examples = undefined;
 
        if (decorator.arguments.length > 0 && decorator.arguments[0]) {
            name = decorator.arguments[0];
        }
        if (decorator.arguments.length > 1 && decorator.arguments[1]) {
            description = decorator.arguments[1];
        }
 
        return {
            description,
            examples,
            name,
            schema: type
        };
    }
 
    private getMethodSuccessExamples() {
        const exampleDecorators = getDecorators(this.node, identifier => identifier.text === 'Example');
        Eif (!exampleDecorators || !exampleDecorators.length) { return undefined; }
        if (exampleDecorators.length > 1) {
            throw new Error(`Only one Example decorator allowed in '${this.getCurrentLocation}' method.`);
        }
 
        const decorator = exampleDecorators[0];
        const argument = decorator.arguments[0];
 
        return this.getExamplesValue(argument);
    }
 
    private supportsPathMethod(method: string) {
        return ['GET', 'POST', 'PATCH', 'DELETE', 'PUT', 'OPTIONS', 'HEAD'].some(m => m === method);
    }
 
    private getExamplesValue(argument: any) {
        const example: any = {};
        argument.properties.forEach((p: any) => {
            example[p.name.text] = this.getInitializerValue(p.initializer);
        });
        return example;
    }
 
    private getMethodTags() {
        const tagsDecorators = getDecorators(this.node, identifier => identifier.text === 'Tags');
        Eif (!tagsDecorators || !tagsDecorators.length) { return []; }
        if (tagsDecorators.length > 1) {
            throw new Error(`Only one Tags decorator allowed in '${this.getCurrentLocation}' method.`);
        }
 
        const decorator = tagsDecorators[0];
        return decorator.arguments;
    }
 
    private getMethodSecurity() {
        const securityDecorators = getDecorators(this.node, identifier => identifier.text === 'Security');
        Eif (!securityDecorators || !securityDecorators.length) { return undefined; }
        if (securityDecorators.length > 1) {
            throw new Error(`Only one Security decorator allowed in '${this.getCurrentLocation}' method.`);
        }
 
        const decorator = securityDecorators[0];
 
        return {
            name: decorator.arguments[0],
            scopes: decorator.arguments[1] ? (decorator.arguments[1] as any).elements.map((e: any) => e.text) : undefined
        };
    }
 
    private getInitializerValue(initializer: any) {
        switch (initializer.kind as ts.SyntaxKind) {
            case ts.SyntaxKind.ArrayLiteralExpression:
                return initializer.elements.map((e: any) => this.getInitializerValue(e));
            case ts.SyntaxKind.StringLiteral:
                return initializer.text;
            case ts.SyntaxKind.TrueKeyword:
                return true;
            case ts.SyntaxKind.FalseKeyword:
                return false;
            case ts.SyntaxKind.NumberKeyword:
            case ts.SyntaxKind.FirstLiteralToken:
                return parseInt(initializer.text, 10);
            case ts.SyntaxKind.ObjectLiteralExpression:
                const nestedObject: any = {};
 
                initializer.properties.forEach((p: any) => {
                    nestedObject[p.name.text] = this.getInitializerValue(p.initializer);
                });
 
                return nestedObject;
            default:
                return undefined;
        }
    }
}