All files / metadata parameterGenerator.ts

42.37% Statements 50/118
9.09% Branches 5/55
40.63% Functions 13/32
38.89% Lines 42/108
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 2581x 1x 1x 1x   1x   1x 1x 1x     1x 1x   1x                   1x                                     1x           1x                                 1x                           1x                                 1x                                 1x                                   1x                                   1x                                   1x                                   1x 1x 1x   1x       1x     1x             1x                                           1x 1x   1x 1x         1x       1x 2x     1x 1x     1x 1x     1x   1x   1x  
import { MetadataGenerator, Parameter, Type } from './metadataGenerator';
import { ResolveType } from './resolveType';
import { getDecoratorName, getDecoratorTextValue } from '../utils/decoratorUtils';
import * as ts from 'typescript';
 
export class ParameterGenerator {
    constructor(
        private readonly parameter: ts.ParameterDeclaration,
        private readonly method: string,
        private readonly path: string
    ) { }
 
    public Generate(): Parameter {
        const decoratorName = getDecoratorName(this.parameter, identifier => this.supportParameterDecorator(identifier.text));
 
        switch (decoratorName) {
            case 'Param':
                return this.getRequestParameter(this.parameter);
            case 'CookieParam':
                return this.getCookieParameter(this.parameter);
            case 'FormParam':
                return this.getFormParameter(this.parameter);
            case 'HeaderParam':
                return this.getHeaderParameter(this.parameter);
            case 'QueryParam':
                return this.getQueryParameter(this.parameter);
            case 'PathParam':
                return this.getPathParameter(this.parameter);
            case 'FileParam':
                return this.getFileParameter(this.parameter);
            case 'FilesParam':
                return this.getFilesParameter(this.parameter);
            case 'Context':
            case 'ContextRequest':
            case 'ContextResponse':
            case 'ContextNext':
            case 'ContextLanguage':
            case 'ContextAccept':
                return this.getContextParameter(this.parameter);
            default:
                return this.getBodyParameter(this.parameter);
        }
    }
 
    private getCurrentLocation() {
        const methodId = (this.parameter.parent as ts.MethodDeclaration).name as ts.Identifier;
        const controllerId = ((this.parameter.parent as ts.MethodDeclaration).parent as ts.ClassDeclaration).name as ts.Identifier;
        return `${controllerId.text}.${methodId.text}`;
    }
 
    private getRequestParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
 
        if (!this.supportsBodyParameters(this.method)) {
            throw new Error(`Param can't support '${this.getCurrentLocation()}' method.`);
        }
        return {
            description: this.getParameterDescription(parameter),
            in: 'param',
            name: getDecoratorTextValue(this.parameter, ident => ident.text === 'Param') || parameterName,
            required: !parameter.questionToken,
            type: type,
            parameterName
        };
    }
 
    private getContextParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'context',
            name: parameterName,
            required: !parameter.questionToken,
            type: type,
            parameterName
        };
    }
 
    private getFileParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
 
        if (!this.supportsBodyParameters(this.method)) {
            throw new Error(`FileParam can't support '${this.getCurrentLocation()}' method.`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'formData',
            name: getDecoratorTextValue(this.parameter, ident => ident.text === 'FileParam') || parameterName,
            required: !parameter.questionToken,
            type: { typeName: 'file' },
            parameterName
        };
    }
 
    private getFilesParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
 
        if (!this.supportsBodyParameters(this.method)) {
            throw new Error(`FilesParam can't support '${this.getCurrentLocation()}' method.`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'formData',
            name: getDecoratorTextValue(this.parameter, ident => ident.text === 'FilesParam') || parameterName,
            required: !parameter.questionToken,
            type: { typeName: 'file' },
            parameterName
        };
    }
 
    private getFormParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
 
        if (!this.supportsBodyParameters(this.method)) {
            throw new Error(`Form can't support '${this.getCurrentLocation()}' method.`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'formData',
            name: getDecoratorTextValue(this.parameter, ident => ident.text === 'FormParam') || parameterName,
            required: !parameter.questionToken,
            type: type,
            parameterName
        };
    }
 
    private getCookieParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
 
        if (!this.supportPathDataType(type)) {
            throw new Error(`Cookie can't support '${this.getCurrentLocation()}' method.`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'cookie',
            name: getDecoratorTextValue(this.parameter, ident => ident.text === 'CookieParam') || parameterName,
            required: !parameter.questionToken,
            type: type,
            parameterName
        };
    }
 
    private getBodyParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
 
        if (!this.supportsBodyParameters(this.method)) {
            throw new Error(`Body can't support ${this.method} method`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'body',
            name: parameterName,
            required: !parameter.questionToken,
            type,
            parameterName
        };
    }
 
    private getHeaderParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
 
        if (!this.supportPathDataType(type)) {
            throw new InvalidParameterException(`Parameter '${parameterName}' can't be passed as a header parameter in '${this.getCurrentLocation()}'.`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'header',
            name: getDecoratorTextValue(this.parameter, ident => ident.text === 'HeaderParam') || parameterName,
            required: !parameter.questionToken,
            type,
            parameterName
        };
    }
 
    private getQueryParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
 
        Iif (!this.supportPathDataType(type)) {
            throw new InvalidParameterException(`Parameter '${parameterName}' can't be passed as a query parameter in '${this.getCurrentLocation()}'.`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'query',
            name: getDecoratorTextValue(this.parameter, ident => ident.text === 'QueryParam') || parameterName,
            required: !parameter.questionToken,
            type,
            parameterName
        };
    }
 
    private getPathParameter(parameter: ts.ParameterDeclaration): Parameter {
        const parameterName = (parameter.name as ts.Identifier).text;
        const type = this.getValidatedType(parameter);
        const pathName = getDecoratorTextValue(this.parameter, ident => ident.text === 'PathParam') || parameterName;
 
        if (!this.supportPathDataType(type)) {
            throw new InvalidParameterException(`Parameter '${parameterName}:${type}' can't be passed as a path parameter in '${this.getCurrentLocation()}'.`);
        }
        if (!this.path.includes(`{${pathName}}`)) {
            throw new Error(`Parameter '${parameterName}' can't macth in path: '${this.path}'`);
        }
 
        return {
            description: this.getParameterDescription(parameter),
            in: 'path',
            name: pathName,
            required: true,
            type,
            parameterName
        };
    }
 
    private getParameterDescription(node: ts.ParameterDeclaration) {
        const symbol = MetadataGenerator.current.typeChecker.getSymbolAtLocation(node.name);
 
        const comments = symbol.getDocumentationComment();
        Eif (comments.length) { return ts.displayPartsToString(comments); }
 
        return '';
    }
 
    private supportsBodyParameters(method: string) {
        return ['POST', 'PUT', 'PATCH'].some(m => m === method);
    }
 
    private supportParameterDecorator(decoratorName: string) {
        return ['HeaderParam', 'QueryParam', 'Param', 'FileParam', 'FilesParam', 'FormParam', 'CookieParam'].some(d => d === decoratorName);
    }
 
    private supportPathDataType(parameterType: Type) {
        return ['string', 'integer', 'long', 'float', 'double', 'date', 'datetime', 'buffer', 'boolean', 'enum'].find(t => t === parameterType.typeName);
    }
 
    private getValidatedType(parameter: ts.ParameterDeclaration) {
        Iif (!parameter.type) {
            throw new Error(`Parameter ${parameter.name} doesn't have a valid type assigned in '${this.getCurrentLocation()}'.`);
        }
        return ResolveType(parameter.type);
    }
}
 
class InvalidParameterException extends Error { }