diff --git a/lib/generator/angular.client/angular.client.generator.ts b/lib/generator/angular.client/angular.client.generator.ts index 83f02b0..5b9bb68 100644 --- a/lib/generator/angular.client/angular.client.generator.ts +++ b/lib/generator/angular.client/angular.client.generator.ts @@ -1,3 +1,5 @@ +const changeCase = require('change-case'); + import { GeneratorConfigBasic } from '../../persistance/generatorconfig.basic'; import { GeneratorConfigAngularClient, AngularClientFilter } from '../../persistance/generatorconfig.angular.client'; @@ -5,7 +7,7 @@ import { ApiParser } from '../../swagger/apiparser.class'; import { ApiDescription } from '../../swagger/entites/apidesciption.class'; import { ControllerType } from '../../swagger/entites/controllertype.class'; import { ComplexType } from '../../swagger/entites/complextype.class'; - +import { RouteType } from '../../swagger/entites/routetype.class'; import { FileManger } from '../filemanager'; import { BaseGenerator } from '../basegenerator'; @@ -49,6 +51,7 @@ export class AngularClientGenerator extends BaseGenerator { createProject: false, projectName: 'angular-client', ngModuleName: 'AngularClient', + controllerNames: [], filter: angularClientFilter }; @@ -84,7 +87,9 @@ export class AngularClientGenerator extends BaseGenerator { projectName = SymbolNameMapper.lower(projectName); let ngModuleName = this.generatorConfig.ngModuleName; - let controllers = this.applyControllerFilter(this.generatorConfig.filter, api.controllers); + let controllers: ControllerType[] = this.createControllersFromRoute(ngModuleName, this.generatorConfig.controllerNames, api.routes); + + controllers = this.applyControllerFilter(this.generatorConfig.filter, controllers); let complexTypes = this.applyReferenceTypeFilter(this.generatorConfig.filter, api.complexTypes); @@ -148,6 +153,48 @@ export class AngularClientGenerator extends BaseGenerator { } */ + + protected createControllersFromRoute(defaultControllerName: string, controllerNames: string[], routes: RouteType[]): ControllerType[] { + let result: ControllerType[] = []; + + if (controllerNames == null || controllerNames == undefined || controllerNames.length == 0) { + // we can't unflatten + let ctrl: ControllerType = new ControllerType(); + ctrl.name = defaultControllerName; + for (let r = 0; r < routes.length; r++) { + let route = routes[r]; + route.operationId = changeCase.camelCase(route.operationId); + ctrl.routes.push(route); + } + + result.push(ctrl); + return result; + } + + for (let c = 0; c < controllerNames.length; c++) { + let controllerName = controllerNames[c]; + if (controllerName.toLowerCase().endsWith("controller")) { + controllerName = controllerName.substring(0, controllerName.length - "controller".length); + } + + let ctrl: ControllerType = new ControllerType(); + ctrl.name = controllerName; + for (let r = 0; r < routes.length; r++) { + let route = routes[r]; + if (route.operationId.startsWith(controllerName)) { + route.operationId = route.operationId.substring(controllerName.length); + route.operationId = changeCase.camelCase(route.operationId); + ctrl.routes.push(route); + } + } + + result.push(ctrl); + } + + + return result; + } + protected applyControllerFilter(filter: AngularClientFilter, controllers: ControllerType[]): ControllerType[] { if (filter === undefined || filter === null) { return controllers; @@ -156,16 +203,62 @@ export class AngularClientGenerator extends BaseGenerator { if (controllers === undefined || controllers === null || controllers.length === 0) { return controllers; } - console.log('applyControllerFilter not implemented'); - return controllers; + + let exculdeController: string[] = filter.exculdeService; + let only: string[] = filter.onlyService; + + if (exculdeController === undefined || exculdeController === null) { + exculdeController = []; + } + if (only === undefined || only === null) { + only = []; + } + + let result: ControllerType[] = []; + for (let k = 0; k < controllers.length; k++) { + let ctrl = controllers[k]; + // excluded + if (only.length == 0 && exculdeController.indexOf(ctrl.name) != -1) { + continue; + } + if (only.length > 0 && only.indexOf(ctrl.name) == -1) { + continue; + } + result.push(ctrl); + } + + return result; } protected applyReferenceTypeFilter(filter: AngularClientFilter, referenceTypes: ComplexType[]): ComplexType[] { if (referenceTypes === undefined || referenceTypes === null || referenceTypes.length === 0) { return referenceTypes; } - console.log('applyReferenceTypeFilter not implemented'); - return referenceTypes; + + let exculdeEntity: string[] = filter.exculdeEntity; + let only: string[] = filter.onlyEntity; + + if (exculdeEntity === undefined || exculdeEntity === null) { + exculdeEntity = []; + } + if (only === undefined || only === null) { + only = []; + } + + let result: ComplexType[] = []; + for (let k = 0; k < referenceTypes.length; k++) { + let entity = referenceTypes[k]; + // excluded + if (only.length == 0 && exculdeEntity.indexOf(entity.name) != -1) { + continue; + } + if (only.length > 0 && only.indexOf(entity.name) == -1) { + continue; + } + result.push(entity); + } + + return result; } } diff --git a/lib/generator/angular.client/angular.client.generator.ts.txt b/lib/generator/angular.client/angular.client.generator.ts.txt deleted file mode 100644 index 6c72aa5..0000000 --- a/lib/generator/angular.client/angular.client.generator.ts.txt +++ /dev/null @@ -1,269 +0,0 @@ -const fs = require('fs'); -const process = require('process'); - -import { GeneratorConfigBasic } from '../../persistance/generatorconfig.basic'; -import { GeneratorConfigSequelizeTSDal } from '../../persistance/generatorconfig.sequelize.ts.dal'; -import { GeneratorConfigAngularClient, AngularClientFilter } from '../../persistance/generatorconfig.angular.client'; - -import { FileManger } from '../filemanager'; -import { BaseGenerator } from '../basegenerator'; -import { RenderTemplate } from '../rendertemplate'; - - -import { SymbolNameMapper } from '../symbolnamemapper'; -import { DBSymbolTable } from '../symboltable/db/dbsymboltable'; -import { DBSymbolTableReader } from '../symboltable/db/dbsymboltable.reader'; -import { SequelizeTsDalTypeMapper } from '../sequelize.ts.dal/sequelize.ts.dal.typemapper.class'; -import { SequelizeTypescriptMapping } from '../sequelize.ts.dal/sequelize.typescript.mapping'; - -export class AngularClientGenerator extends BaseGenerator { - protected generatorConfig: GeneratorConfigAngularClient; - protected parentGeneratorConfig: GeneratorConfigExpressTSRoutes; - protected metadataSymbolTable: MetadataSymbolTable; - protected dbSymbolTable: DBSymbolTable; - - constructor(generatorConfigBasic: GeneratorConfigBasic, nicassaJson: string) { - super(generatorConfigBasic, nicassaJson); - this.generatorConfig = generatorConfigBasic; - if (this.generatorConfig !== undefined && this.generatorConfig !== null) { - if (this.generatorConfig.filter === undefined || this.generatorConfig.filter === null) { - let defaultCfg = this.getDefaultConfig(''); - this.generatorConfig.filter = defaultCfg.filter; - } - } - this.templateDir = __dirname + '/templates'; - } - - public getDefaultConfig(name: string): GeneratorConfigAngularClient { - let angularClientFilter: AngularClientFilter = { - exculdeEntity: [], - exculdeService: [], - onlyEntity: [], - onlyService: [] - } - - let type = "angular.client"; - - let result: GeneratorConfigAngularClient = { - name: name, - type: type, - active: true, - customErrorHandler: false, - targetDir: './angular-client', - parentServerGeneratorConfigName: 'express.ts.routes', - cleanTargetDir: false, - createProject: false, - projectName: 'angular-client', - ngModuleName: 'AngularClient', - filter: angularClientFilter - }; - - return result; - } - - protected async generateCode(): Promise { - this.parentGeneratorConfig = BaseGenerator.getGeneratorByNameFromString - (this.nicassaJson, this.generatorConfig.parentServerGeneratorConfigName); - - this.metadataSymbolTable = MetadataSymbolTableReader.readFromJsonString(this.nicassaJson); - this.setLengthToMetaData(); - - let createPackageJson: boolean = false; - let createIndex: boolean = false; - let createProject: boolean = this.generatorConfig.createProject; - let createConfiguration: boolean = false; - let createErrorReporter: boolean = false; - let customErrorHandler: boolean = false; - if (createProject) { - createPackageJson = !FileManger.fileExistInProjectDir(this, 'package.json'); - createIndex = !FileManger.fileExistInProjectDir(this, 'index.ts'); - createConfiguration = !FileManger.fileExistInProjectDir(this, 'configuration.ts'); - createErrorReporter = !FileManger.fileExistInProjectDir(this, 'errorreporter.ts'); - } - if (this.generatorConfig.customErrorHandler != null && this.generatorConfig.customErrorHandler !== undefined && - this.generatorConfig.customErrorHandler == true) { - customErrorHandler = true; - } - let projectName = this.generatorConfig.projectName; - if (projectName === undefined || projectName === null) { - projectName = 'undefined'; - } - projectName = SymbolNameMapper.titleCase(projectName); - projectName = SymbolNameMapper.headerCase(projectName); - projectName = SymbolNameMapper.lower(projectName); - let ngModuleName = this.generatorConfig.ngModuleName; - - let controllers = this.applyControllerFilter(this.generatorConfig.filter, this.metadataSymbolTable.controllers); - let referenceTypes = this.applyReferenceTypeFilter(this.generatorConfig.filter, this.metadataSymbolTable.referenceTypes); - - - let data = { - controllers: controllers, - referenceTypes: referenceTypes, - projectName: projectName, - ngModuleName: ngModuleName, - customErrorHandler: customErrorHandler - }; - - // idea from - // https://offering.solutions/blog/articles/2016/02/01/consuming-a-rest-api-with-angular-http-service-in-typescript/ - - await RenderTemplate.renderTemplate(true, this, 'entities.ts.ejs', data); - await RenderTemplate.renderTemplate(true, this, 'services.ts.ejs', data); - await RenderTemplate.renderTemplate(createPackageJson, this, 'package.json.ejs', data); - await RenderTemplate.renderTemplate(createIndex, this, 'index.ts.ejs', data); - await RenderTemplate.renderTemplate(createProject, this, 'generated.exports.ts.ejs', data); - await RenderTemplate.renderTemplate(createConfiguration, this, 'configuration.ts.ejs', data); - await RenderTemplate.renderTemplate(createErrorReporter, this, 'errorreporter.ts.ejs', data); - await RenderTemplate.renderTemplate(true, this, 'ng.module.ts.ejs', data); - - return await true; - } - - - protected applyControllerFilter(filter: AngularClientFilter, controllers: ControllerSymbol[]): ControllerSymbol[] { - if (filter === undefined || filter === null) { - return controllers; - } - - if (controllers === undefined || controllers === null || controllers.length === 0) { - return controllers; - } - - let exculdeController: string[] = filter.exculdeService; - let only: string[] = filter.onlyService; - - if (exculdeController === undefined || exculdeController === null) { - exculdeController = []; - } - if (only === undefined || only === null) { - only = []; - } - - let result: ControllerSymbol[] = []; - for (let k = 0; k < controllers.length; k++) { - let ctrl = controllers[k]; - // excluded - if (only.length == 0 && exculdeController.indexOf(ctrl.name) != -1) { - continue; - } - if (only.length > 0 && only.indexOf(ctrl.name) == -1) { - continue; - } - result.push(ctrl); - } - - return result; - } - - protected applyReferenceTypeFilter(filter: AngularClientFilter, referenceTypes: ReferenceTypeSymbol[]): ReferenceTypeSymbol[] { - if (referenceTypes === undefined || referenceTypes === null || referenceTypes.length === 0) { - return referenceTypes; - } - - let exculdeEntity: string[] = filter.exculdeEntity; - let only: string[] = filter.onlyEntity; - - if (exculdeEntity === undefined || exculdeEntity === null) { - exculdeEntity = []; - } - if (only === undefined || only === null) { - only = []; - } - - let result: ReferenceTypeSymbol[] = []; - for (let k = 0; k < referenceTypes.length; k++) { - let entity = referenceTypes[k]; - // excluded - if (only.length == 0 && exculdeEntity.indexOf(entity.name) != -1) { - continue; - } - if (only.length > 0 && only.indexOf(entity.name) == -1) { - continue; - } - result.push(entity); - } - - return result; - } - - protected setLengthToMetaData() { - if (this.parentGeneratorConfig.nicassaParserDBFile === undefined || this.parentGeneratorConfig.nicassaParserDBFile === null) { - return; - } - - if (!fs.existsSync(this.parentGeneratorConfig.nicassaParserDBFile)) { - console.error('error: can\'t find nicassaParserDBFile: ' + this.parentGeneratorConfig.nicassaParserDBFile + '\''); - process.exit(-1); - } - - let json = null; - try { - json = fs.readFileSync(this.parentGeneratorConfig.nicassaParserDBFile); - } catch (err) { - console.error('error: can\'t read nicassaParserDBFile: ' + this.parentGeneratorConfig.nicassaParserDBFile + '\''); - process.exit(-1); - } - - if (this.parentGeneratorConfig.nicassaParserDBGeneratorName === undefined || this.parentGeneratorConfig.nicassaParserDBGeneratorName === null) { - console.error('error: can\'t find nicassaParserDBGeneratorName for the nicassaParserDBFile: ' + this.parentGeneratorConfig.nicassaParserDBFile + '\''); - process.exit(-1); - } - - // we need the config... - let gen: GeneratorConfigSequelizeTSDal = BaseGenerator.getGeneratorByName - (this.parentGeneratorConfig.nicassaParserDBFile, this.parentGeneratorConfig.nicassaParserDBGeneratorName); - - if (gen === undefined || gen === null) { - console.error('error: can\'t find generator with name ' + - this.parentGeneratorConfig.nicassaParserDBGeneratorName + ' for the nicassaParserDBFile: ' + this.parentGeneratorConfig.nicassaParserDBFile + '\''); - process.exit(-1); - } - - // .. to map with the settings - let dataTypeMapping = SequelizeTypescriptMapping.dataTypeMapping; - let typeMapper: SequelizeTsDalTypeMapper = new SequelizeTsDalTypeMapper(gen, dataTypeMapping); - - this.dbSymbolTable = DBSymbolTableReader.readFromJsonString(json, gen.filter, typeMapper); - this.updateMetaSymbolTableLengthFromDbSymbolTable(this.metadataSymbolTable, this.dbSymbolTable); - } - - protected updateMetaSymbolTableLengthFromDbSymbolTable(meta: MetadataSymbolTable, db: DBSymbolTable) { - if (db.entities === undefined || db.entities === null || db.entities.length === 0) { - return; - } - - if (meta.referenceTypes === undefined || meta.referenceTypes === null || meta.referenceTypes.length === 0) { - return; - } - - // create the map - let entityColumnMap: any = {}; - for (let i = 0; i < db.entities.length; i++) { - let entity = db.entities[i]; - entityColumnMap[entity.getMappedName('TypeScript')] = {}; - for (let k = 0; k < entity.columns.length; k++) { - let column = entity.columns[k]; - if (column.length === undefined || column.length === null || column.length < 0) { - continue; - } - entityColumnMap[entity.getMappedName('TypeScript')][column.getMappedName('TypeScript')] = column.length; - } - } - - for (let i = 0; i < meta.referenceTypes.length; i++) { - let ref = meta.referenceTypes[i]; - if (!entityColumnMap.hasOwnProperty(ref.name)) { - continue; - } - for (let k = 0; k < ref.properties.length; k++) { - let prop = ref.properties[k]; - if (!entityColumnMap[ref.name].hasOwnProperty(prop.name)) { - continue; - } - prop.length = entityColumnMap[ref.name][prop.name]; - } - } - } -} - diff --git a/lib/generator/angular.client/templates/configuration.ts.ejs b/lib/generator/angular.client/templates/configuration.ts.ejs index f053768..1212038 100644 --- a/lib/generator/angular.client/templates/configuration.ts.ejs +++ b/lib/generator/angular.client/templates/configuration.ts.ejs @@ -4,6 +4,8 @@ import { Injectable } from '@angular/core'; export class Configuration { public static ServerWithApiUrl: string = 'http://myserver:1234/basepath'; + public token: string = ''; + public url(): string { return Configuration.ServerWithApiUrl; } diff --git a/lib/generator/angular.client/templates/package.json.ejs b/lib/generator/angular.client/templates/package.json.ejs index f39b54b..bd393a1 100644 --- a/lib/generator/angular.client/templates/package.json.ejs +++ b/lib/generator/angular.client/templates/package.json.ejs @@ -11,18 +11,18 @@ "license": "ISC", "private": true, "dependencies": { - "@angular/common": "2.2.3", - "@angular/core": "2.2.3", - "@angular/http": "2.2.3", - "core-js": "^2.4.1", - "rxjs": "5.0.0-beta.12", - "ts-helpers": "^1.1.1", - "zone.js": "^0.6.23" + "@angular/common": "4.1.3", + "@angular/core": "4.1.3", + "@angular/http": "4.1.3", + "core-js": "2.4.1", + "rxjs": "5.2.0", + "ts-helpers": "1.1.2", + "zone.js": "0.8.5" }, "devDependencies": { - "@types/node": "^6.0.42", - "codelyzer": "~2.0.0-beta.1", - "typescript": "~2.0.3" + "@types/node": "^7.0.5", + "codelyzer": "^3.0.1", + "typescript": "^2.3.2" } } diff --git a/lib/generator/angular.client/templates/services.ts.ejs b/lib/generator/angular.client/templates/services.ts.ejs index f3ebd5e..a38c898 100644 --- a/lib/generator/angular.client/templates/services.ts.ejs +++ b/lib/generator/angular.client/templates/services.ts.ejs @@ -10,7 +10,7 @@ import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Injectable } from '@angular/core'; -import { Http, Response, Headers } from '@angular/http'; +import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Configuration } from './configuration'; import { ErrorReporter } from './errorreporter'; @@ -27,17 +27,19 @@ complexTypes.forEach(function(type){%> @Injectable() export class <%- ctrl.name%>Service { private actionUrl: string; - private headers: Headers; constructor(private _http: Http, private _configuration: Configuration, private _errorreporter: ErrorReporter) { this.actionUrl = this._configuration.url() + '<%- ctrl.path%>'; - this.headers = new Headers(); - this.headers.append('Content-Type', 'application/json'); - this.headers.append('Accept', 'application/json'); } + private createHeaders() : Headers { + let headers: Headers = new Headers(); + headers.append('Content-Type', 'application/json'); + headers.append('Accept', 'application/json'); + return headers(); + } <% ctrl.routes.forEach(function(method){%> public <%- method.operationId%> = (<% @@ -65,11 +67,12 @@ ctrl.routes.forEach(function(method){%> resultType = response.getMappedType('TypeScript'); resultTypeIsPrimitive = response.isPrimitive; if(response.isArray) { - resultType += []; + resultType += "[]"; } resultTypeHttp = resultType; } - %><%- resultType %>> => {<% + %><%- resultType %>> => { + let _headers: Headers = this.createHeaders();<% if(method.response.length>1) {%> /* warning <%- method.response.length %> response types found - currently only using the very first one @@ -81,10 +84,10 @@ ctrl.routes.forEach(function(method){%> var param = method.getBodyParameter(); needBody = true; if(param != null) { body = param.name; } %> - let body: any = <%- body; %>;<%} + let _body: any = <%- body; %>;<%} if(method.hasParameterType('path')) { %> - var url = this.actionUrl + this.__buildPath('<%- method.path%>'<% + let _url = this.actionUrl + this.__buildPath('<%- method.pathNoSlash()%>'<% var buildPathParams = ''; method.parameter.forEach(function(pathParam){ if(pathParam.in == 'path') { @@ -95,7 +98,7 @@ if(method.hasParameterType('path')) { }); if(buildPathParams !='') {%><%- buildPathParams; %><%} %>);<%} else {%> - var url = this.actionUrl + '<%- method.path%>';<% + let _url = this.actionUrl + '<%- method.pathNoSlash()%>';<% }%><% if(method.hasParameterType('query')) {%> url = this.__buildQuery(url<% @@ -108,52 +111,69 @@ if(method.hasParameterType('path')) { } }); %><%- buildQueryParams; %>);%><% +}%><% + if(method.hasParameterType('header')) { + method.parameter.forEach(function(headerParam){ + if(headerParam.in == 'header') {%> + _headers.append('<%- headerParam.name%>', <%- headerParam.name%> ? encodeURI(<%- headerParam.name%>) : ''); + <%}});%><% +}%><% if(method.security == 'jwt') {%> + _headers.append('x-access-token', this._configuration.token); + %><% }%> - - return this._http.<%- method.verb%>(url<%if(needBody) {%>, body<%}%>) - .map((response: Response) => <<%- resultTypeHttp %>> ( - response<% + return this._http.<%- method.verb%>(_url<%if(needBody) {%>, _body<%}%>, _headers) + .map((response: Response) => <<%- resultTypeHttp %>> ( <% if(resultTypeIsPrimitive){ - %>.text()<% + %>response.text()<% }else{ - %>.json()<%}%> - ) + %>response.json()<%}%> )) .catch((error: Response) => this._errorreporter.handleError(error)); } <%});%><%if(needbuildQuery) {%> private __buildQuery(url: any, ...params: any[]): string { - if( param === undefined || param === null || params.length == 0) { + if (params === undefined || params === null || params.length === 0) { return url; } + let delimiter = '?'; + for (let i = 0; i < params.length; i += 2) { + let key: string = params[i]; + let value: any = params[i+1]; + key = encodeURI(key); - throw 'not implemented to copy paste later'; - - for (var i = 0; i < params.length; i+=2) { - sum += params[i]; - } + if(value == null || value === undefined) { + value = ''; + } + value = encodeURI(value); + url += delimter + key + '=' + value; + let arr = url.split('{' + key + '}'); + url = arr[0] + value + arr[1]; - return encodeURI(param); + delimiter = '&'; + } + return url; }<% }%><%if(needbuildPath) {%> private __buildPath(url: any, ...params: any[]): string { - if( param === undefined || param === null || params.length == 0) { + if (params === undefined || params === null || params.length === 0) { return url; } + for (let i = 0; i < params.length; i += 2) { + let key: string = params[i]; + let value: any = params[i + 1]; + if (value == null || value === undefined) { + value = ''; + } + value = encodeURI(value); - throw 'not implemented to copy paste later'; - - for (var i = 0; i < params.length; i+=2) { - sum += params[i]; + let arr = url.split('{' + key + '}'); + url = arr[0] + value + arr[1]; } - - - - return encodeURI(param); + return url; }<% }%> diff --git a/lib/persistance/generatorconfig.angular.client.ts b/lib/persistance/generatorconfig.angular.client.ts index f9edf3c..6bd26d7 100644 --- a/lib/persistance/generatorconfig.angular.client.ts +++ b/lib/persistance/generatorconfig.angular.client.ts @@ -14,5 +14,6 @@ export interface GeneratorConfigAngularClient extends GeneratorConfigBasic { createProject: boolean; ngModuleName: string; projectName?: string; + controllerNames: string[]; filter?: AngularClientFilter; } diff --git a/lib/swagger/apiparser.class.ts b/lib/swagger/apiparser.class.ts index 7dbffc1..a93e702 100644 --- a/lib/swagger/apiparser.class.ts +++ b/lib/swagger/apiparser.class.ts @@ -7,7 +7,6 @@ import * as SwaggerParser from 'swagger-parser'; import { ApiDescription } from './entites/apidesciption.class'; import { ComplexType } from './entites/complextype.class'; import { PropertyType } from './entites/propertytype.class'; -import { ControllerType } from './entites/controllertype.class'; import { ParameterType } from './entites/parametertype.class'; import { ResponseType } from './entites/responsetype.class'; @@ -27,27 +26,18 @@ export class ApiParser { result.complexTypes = this.parseDefinitions(swagger.definitions); } - if (swagger.paths != null || swagger.paths !== undefined) { - result.controllers = this.parseRoutes(swagger.paths); - } + result.routes = this.parseRoutes(swagger.paths); return await result; } - private parseRoutes(paths: any): ControllerType[] { - let result: ControllerType[] = []; - let controllerDict: any = {}; + private parseRoutes(paths: any): RouteType[] { + let result: RouteType[] = []; + for (let path in paths) { - let name = this.getControllerNameFromPath(path); - if (!controllerDict.hasOwnProperty(name)) { - let controller = new ControllerType(); - controller.name = name; - controllerDict[name] = controller; - result.push(controller); - } let data = paths[path]; - controllerDict[name].routes.push(this.parseRoute(path, data)); + result.push(this.parseRoute(path, data)); } return result; } @@ -77,6 +67,17 @@ export class ApiParser { let parameters = this.parseParameters(operation.parameters); route.parameter = parameters; } + + if (operation.security != null && + operation.security !== undefined&& + operation.security.length > 0) { + for (let i = 0; i < operation.security.length; i++) { + let item: any = operation.security[i]; + if (item.hasOwnProperty('jwt')) { + route.security = 'jwt'; + } + } + } } // this must be here - only one verb! break; @@ -143,15 +144,6 @@ export class ApiParser { return result; } - private getControllerNameFromPath(path: string): string { - let pathArr = path.split('/'); - let name = pathArr[0]; - if (name == ''){ - name = pathArr[1]; - } - return name; - } - private parseDefinitions(definitions: any): ComplexType[] { let result: ComplexType[] = []; diff --git a/lib/swagger/entites/apidesciption.class.ts b/lib/swagger/entites/apidesciption.class.ts index 28fd786..397cc3a 100644 --- a/lib/swagger/entites/apidesciption.class.ts +++ b/lib/swagger/entites/apidesciption.class.ts @@ -1,7 +1,7 @@ import { ComplexType } from './complextype.class'; -import { ControllerType } from './controllertype.class'; +import { RouteType } from './routetype.class'; export class ApiDescription { complexTypes: ComplexType[] = []; - controllers: ControllerType[] = []; -} \ No newline at end of file + routes: RouteType[]; +} diff --git a/lib/swagger/entites/routetype.class.ts b/lib/swagger/entites/routetype.class.ts index c67c43e..78402b7 100644 --- a/lib/swagger/entites/routetype.class.ts +++ b/lib/swagger/entites/routetype.class.ts @@ -1,12 +1,15 @@ import { ParameterType, InType } from './parametertype.class'; import { ResponseType } from './responsetype.class'; +export type SecurityType = '' | 'jwt'; + export class RouteType { path: string; verb: string; operationId: string; parameter: ParameterType[] = []; response: ResponseType[] = []; + security: SecurityType = ''; getBodyParameter(): ParameterType | null { for (let parameter of this.parameter) { @@ -26,4 +29,8 @@ export class RouteType { } return false; } + + pathNoSlash(): string { + return this.path.replace(/^\/|\/$/g, ''); + } } diff --git a/package.json b/package.json index 96bbab8..f522989 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "nicassa-generator": "launcher.js" }, "scripts": { - "gentest-alltypes": "cd test && cd alltypes && tsoa swagger", + "gentest-alltypes": "cd test && cd alltypes && tsoa swagger", "gentest-alltypes-optional": "cd test && cd alltypesoptional && tsoa swagger", "gentest-alltypes-array": "cd test && cd alltypesarray && tsoa swagger", "gentest-alltypes-array-optional": "cd test && cd alltypesarrayoptional && tsoa swagger", @@ -38,8 +38,8 @@ "pg-hstore": "^2.3.2", "prompt": "^1.0.0", "sqlite3": "^3.1.8", - "tedious": "^2.0.0", "swagger-parser": "^3.4.1", + "tedious": "^2.0.0", "ts-node": "^3.1.0", "typescript": "^2.4.1" }, diff --git a/test/test.ts b/test/test.ts index 2ca0926..367c3be 100644 --- a/test/test.ts +++ b/test/test.ts @@ -1,7 +1,7 @@ -import { ControllerType } from './../lib/swagger/entites/controllertype.class'; +import { RouteType } from '../lib/swagger/entites/routetype.class'; +import { ApiParser } from './../lib/swagger/apiparser.class'; import { ApiDescription } from './../lib/swagger/entites/apidesciption.class'; import { ComplexType } from './../lib/swagger/entites/complextype.class'; -import { ApiParser } from './../lib/swagger/apiparser.class'; main(); @@ -30,16 +30,12 @@ async function main() { } } - for (let k = 0; k < api.controllers.length; k++) { - let controller: ControllerType = api.controllers[k]; - // console.log(type.type); - for (let r = 0; r < controller.routes.length; r++) { - // let route = controller.routes[r]; - // console.log(route.path, route.response); - // console.log(route); - } + for (let k = 0; k < api.routes.length; k++) { + let route: RouteType = api.routes[k]; + route = route; + // console.log(route); } // console.log(api); -} \ No newline at end of file +}