All files / swagger generator.ts

70.47% Statements 105/149
45.45% Branches 30/66
69.44% Functions 25/36
70.31% Lines 90/128
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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278            1x 1x 1x   1x 1x   1x                                                   1x 1x                   1x       1x 1x 1x 1x 1x   1x                   1x     1x 1x 1x 2x 2x     3x     2x         1x     1x 1x   1x 1x 2x 2x 2x       1x     2x 2x 2x   2x 2x 2x           2x 1x 1x   2x 1x                                     2x         2x       1x 1x             1x 1x     1x     1x   1x     2x 2x   2x 3x 3x 2x   3x     2x     1x                         2x 2x   2x 2x     2x 2x   2x         2x             1x 2x 2x     1x 8x 8x 5x     3x 3x       3x 3x       3x 3x     1x 8x                                 8x     1x       1x       1x 3x   1x  
import { SwaggerConfig } from '../config';
import {
    Metadata, Type, ArrayType, ReferenceType, EnumerateType,
    Property, Method, Parameter, ResponseType
} from '../metadata/metadataGenerator';
import { Swagger } from './swagger';
import * as fs from 'fs';
import * as mkdirp from 'mkdirp';
import * as YAML from 'yamljs';
 
export class SpecGenerator {
    constructor(private readonly metadata: Metadata, private readonly config: SwaggerConfig) { }
 
    public generate(swaggerDir: string, yaml: boolean): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            mkdirp(swaggerDir, (dirErr: any) => {
                if (dirErr) {
                    throw dirErr;
                }
                const spec = this.getSpec();
                fs.writeFile(`${swaggerDir}/swagger.json`, JSON.stringify(spec, null, '\t'), (err: any) => {
                    if (err) {
                        reject(err);
                    }
                    if (yaml) {
                        fs.writeFile(`${swaggerDir}/swagger.yaml`, YAML.stringify(spec), (errYaml: any) => {
                            if (errYaml) {
                                reject(errYaml);
                            }
                            resolve();
                        });
                    } else {
                        resolve();
                    }
                });
            });
        });
    }
 
    public getSpec() {
        let spec: Swagger.Spec = {
            basePath: this.config.basePath,
            consumes: ['application/json'],
            definitions: this.buildDefinitions(),
            info: {},
            paths: this.buildPaths(),
            produces: ['application/json'],
            swagger: '2.0'
        };
 
        spec.securityDefinitions = this.config.securityDefinitions
            ? this.config.securityDefinitions
            : {};
 
        Eif (this.config.description) { spec.info.description = this.config.description; }
        Eif (this.config.license) { spec.info.license = { name: this.config.license }; }
        Eif (this.config.name) { spec.info.title = this.config.name; }
        Eif (this.config.version) { spec.info.version = this.config.version; }
        Eif (this.config.host) { spec.host = this.config.host; }
 
        Iif (this.config.spec) {
            this.config.specMerging = this.config.specMerging || 'immediate';
            const mergeFuncs: { [key: string]: Function } = {
                immediate: Object.assign,
                recursive: require('merge').recursive,
            };
 
            spec = mergeFuncs[this.config.specMerging](spec, this.config.spec);
        }
 
        return spec;
    }
 
    private buildDefinitions() {
        const definitions: { [definitionsName: string]: Swagger.Schema } = {};
        Object.keys(this.metadata.ReferenceTypes).map(typeName => {
            const referenceType = this.metadata.ReferenceTypes[typeName];
            definitions[referenceType.typeName] = {
                description: referenceType.description,
                properties: this.buildProperties(referenceType.properties),
                required: referenceType.properties.filter(p => p.required).map(p => p.name),
                type: 'object'
            };
            Iif (referenceType.additionalProperties) {
                definitions[referenceType.typeName].additionalProperties = this.buildAdditionalProperties(referenceType.additionalProperties);
            }
        });
 
        return definitions;
    }
 
    private buildPaths() {
        const paths: { [pathName: string]: Swagger.Path } = {};
 
        this.metadata.Controllers.forEach(controller => {
            controller.methods.forEach(method => {
                const path = `${controller.path ? `/${controller.path}` : ''}${method.path}`;
                paths[path] = paths[path] || {};
                this.buildPathMethod(controller.name, method, paths[path]);
            });
        });
 
        return paths;
    }
 
    private buildPathMethod(controllerName: string, method: Method, pathObject: any) {
        const pathMethod: any = pathObject[method.method] = this.buildOperation(controllerName, method);
        pathMethod.description = method.description;
 
        Iif (method.deprecated) { pathMethod.deprecated = method.deprecated; }
        Iif (method.tags.length) { pathMethod.tags = method.tags; }
        Iif (method.security) {
            const security: any = {};
            security[method.security.name] = method.security.scopes ? method.security.scopes : [];
            pathMethod.security = [security];
        }
 
        pathMethod.parameters = method.parameters
            .filter(p => (p.in !== 'param'))
            .map(p => this.buildParameter(p));
 
        method.parameters
            .filter(p => (p.in === 'param'))
            .forEach(p => {
                pathMethod.parameters.push(this.buildParameter({
                    description: p.description,
                    in: 'query',
                    name: p.name,
                    parameterName: p.parameterName,
                    required: false,
                    type: p.type
                }));
                pathMethod.parameters.push(this.buildParameter({
                    description: p.description,
                    in: 'formData',
                    name: p.name,
                    parameterName: p.parameterName,
                    required: false,
                    type: p.type
                }));
            });
        Iif (method.parameters.some(p => (p.in === 'file' || p.in === 'files'))) {
            pathMethod.consumes = pathMethod.consumes || [];
            pathMethod.consumes.push('multipart/form-data');
        }
 
        Iif (pathMethod.parameters.filter((p: Swagger.BaseParameter) => p.in === 'body').length > 1) {
            throw new Error('Only one body parameter allowed per controller method.');
        }
    }
    private buildParameter(parameter: Parameter): Swagger.Parameter {
        const swaggerParameter: any = {
            description: parameter.description,
            in: parameter.in,
            name: parameter.name,
            required: parameter.required
        };
 
        const parameterType = this.getSwaggerType(parameter.type);
        Iif (parameterType.$ref) {
            swaggerParameter.schema = parameterType;
        } else {
            swaggerParameter.type = parameterType.type;
        }
 
        Iif (parameterType.format) { swaggerParameter.format = parameterType.format; }
 
        return swaggerParameter;
    }
 
    private buildProperties(properties: Property[]) {
        const swaggerProperties: { [propertyName: string]: Swagger.Schema } = {};
 
        properties.forEach(property => {
            const swaggerType = this.getSwaggerType(property.type);
            if (!swaggerType.$ref) {
                swaggerType.description = property.description;
            }
            swaggerProperties[property.name] = swaggerType;
        });
 
        return swaggerProperties;
    }
 
    private buildAdditionalProperties(properties: Property[]) {
        const swaggerAdditionalProperties: { [ref: string]: string } = {};
 
        properties.forEach(property => {
            const swaggerType = this.getSwaggerType(property.type);
            if (swaggerType.$ref) {
                swaggerAdditionalProperties['$ref'] = swaggerType.$ref;
            }
        });
 
        return swaggerAdditionalProperties;
    }
 
    private buildOperation(controllerName: string, method: Method) {
        const responses: any = {};
 
        method.responses.forEach((res: ResponseType) => {
            responses[res.name] = {
                description: res.description
            };
            Eif (res.schema && this.getSwaggerType(res.schema).type !== 'void') {
                responses[res.name]['schema'] = this.getSwaggerType(res.schema);
            }
            Iif (res.examples) {
                responses[res.name]['examples'] = { 'application/json': res.examples };
            }
        });
 
        return {
            operationId: this.getOperationId(controllerName, method.name),
            produces: ['application/json'],
            responses: responses
        };
    }
 
    private getOperationId(controllerName: string, methodName: string) {
        const controllerNameWithoutSuffix = controllerName.replace(new RegExp('Controller$'), '');
        return `${controllerNameWithoutSuffix}${methodName.charAt(0).toUpperCase() + methodName.substr(1)}`;
    }
 
    private getSwaggerType(type: Type) {
        const swaggerType = this.getSwaggerTypeForPrimitiveType(type);
        if (swaggerType) {
            return swaggerType;
        }
 
        const arrayType = type as ArrayType;
        Iif (arrayType.elementType) {
            return this.getSwaggerTypeForArrayType(arrayType);
        }
 
        const enumType = type as EnumerateType;
        Iif (enumType.enumMembers) {
            return this.getSwaggerTypeForEnumType(enumType);
        }
 
        const refType = this.getSwaggerTypeForReferenceType(type as ReferenceType);
        return refType;
    }
 
    private getSwaggerTypeForPrimitiveType(type: Type) {
        const typeMap: { [name: string]: Swagger.Schema } = {
            binary: { type: 'string', format: 'binary' },
            boolean: { type: 'boolean' },
            buffer: { type: 'string', format: 'base64' },
            byte: { type: 'string', format: 'byte' },
            date: { type: 'string', format: 'date' },
            datetime: { type: 'string', format: 'date-time' },
            double: { type: 'number', format: 'double' },
            file: { type: 'file' },
            float: { type: 'number', format: 'float' },
            integer: { type: 'integer', format: 'int32' },
            long: { type: 'integer', format: 'int64' },
            object: { type: 'object' },
            string: { type: 'string' },
            void: { type: 'void' },
        };
 
        return typeMap[type.typeName];
    }
 
    private getSwaggerTypeForArrayType(arrayType: ArrayType): Swagger.Schema {
        return { type: 'array', items: this.getSwaggerType(arrayType.elementType) };
    }
 
    private getSwaggerTypeForEnumType(enumType: EnumerateType): Swagger.Schema {
        return { type: 'string', enum: enumType.enumMembers.map(member => member as string) as [string] };
    }
 
    private getSwaggerTypeForReferenceType(referenceType: ReferenceType): Swagger.Schema {
        return { $ref: `#/definitions/${referenceType.typeName}` };
    }
}