diff --git a/bin/swagger2js.js b/bin/swagger2js.js index 9020fc00..42b4454b 100755 --- a/bin/swagger2js.js +++ b/bin/swagger2js.js @@ -1,12 +1,13 @@ #!/usr/bin/env node -var path = require('path'); -var fs = require('fs'); -var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib'); -var updateNotifier = require('update-notifier'); +const path = require('path'); +const fs = require('fs'); +const updateNotifier = require('update-notifier'); +const pkg = require('../package.json'); -//1. Update Notifier -var pkg = require('../package.json'); +const lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib'); + +// Update Notifier updateNotifier({packageName: pkg.name, packageVersion: pkg.version}).notify(); -//4. CLI Script +// CLI Script require(lib + '/cli.js'); \ No newline at end of file diff --git a/circle.yml b/circle.yml index 65bc161e..15aed191 100644 --- a/circle.yml +++ b/circle.yml @@ -1,6 +1,6 @@ machine: node: - version: 5.7.0 + version: 14.16.0 dependencies: post: - npm install grunt-cli -g diff --git a/lib/cli.js b/lib/cli.js index 9a907e50..979d0e84 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -4,7 +4,7 @@ const fs = require('fs'); const pkg = require('../package.json'); const cli = require('commander'); const yaml = require('js-yaml').safeLoad; -const CodeGen = require('./codegen').CodeGen; +const CodeGen = require('./codegen.js').CodeGen; cli .version(pkg.version) @@ -17,14 +17,14 @@ cli .option('-l, --lint', 'Whether or not to run jslint on the generated code [false]') .option('-b, --beautify', 'Whether or not to beautify the generated code [false]') .action((file, imports, options) => { - const fnName = 'get' + options.type.charAt(0).toUpperCase() + options.type.substr(1) + 'Code'; + const fnName = `get${options.type.charAt(0).toUpperCase()}${options.type.substr(1)}Code`; const fn = CodeGen[fnName]; options.lint = options.lint || false; options.beautify = options.beautify || false; const content = fs.readFileSync(file, 'utf-8'); - var swagger; + let swagger; try { swagger = JSON.parse(content); } catch (e) { @@ -34,7 +34,7 @@ cli const result = fn({ moduleName: options.module, className: options.class, - swagger: swagger, + swagger, lint: options.lint, beautify: options.beautify }); diff --git a/lib/codegen.js b/lib/codegen.js index 94edd8d6..fb155204 100644 --- a/lib/codegen.js +++ b/lib/codegen.js @@ -1,41 +1,38 @@ 'use strict'; -var fs = require('fs'); -var Mustache = require('mustache'); -var beautify = require('js-beautify').js_beautify; -var lint = require('jshint').JSHINT; -var _ = require('lodash'); -var ts = require('./typescript'); -var flow = require('./flow'); +const fs = require('fs'); +const Mustache = require('mustache'); +const beautify = require('js-beautify').js_beautify; +const lint = require('jshint').JSHINT; +const _ = require('lodash'); +const ts = require('./typescript.js'); +const flow = require('./flow.js'); +const normalizeName = id => id.replace(/\.|\-|\{|\}|\s/g, '_'); -var normalizeName = function(id) { - return id.replace(/\.|\-|\{|\}|\s/g, '_'); -}; - -var getPathToMethodName = function(opts, m, path){ +const getPathToMethodName = (opts, m, path) => { if(path === '/' || path === '') { return m; } // clean url path for requests ending with '/' - var cleanPath = path.replace(/\/$/, ''); + const cleanPath = path.replace(/\/$/, ''); - var segments = cleanPath.split('/').slice(1); - segments = _.transform(segments, function (result, segment) { + let segments = cleanPath.split('/').slice(1); + segments = _.transform(segments, (result, segment) => { if (segment[0] === '{' && segment[segment.length - 1] === '}') { - segment = 'by' + segment[1].toUpperCase() + segment.substring(2, segment.length - 1); + segment = `by${segment[1].toUpperCase()}${segment.substring(2, segment.length - 1)}`; } result.push(segment); }); - var result = _.camelCase(segments.join('-')); + const result = _.camelCase(segments.join('-')); return m.toLowerCase() + result[0].toUpperCase() + result.substring(1); }; -var getViewForSwagger2 = function(opts, type){ - var swagger = opts.swagger; - var methods = []; - var authorizedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND']; - var data = { +const getViewForSwagger2 = (opts, type) => { + const swagger = opts.swagger; + const methods = []; + const authorizedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND']; + const data = { isNode: type === 'node' || type === 'react', isES6: opts.isES6 || type === 'react', description: swagger.info.description, @@ -43,68 +40,65 @@ var getViewForSwagger2 = function(opts, type){ moduleName: opts.moduleName, className: opts.className, imports: opts.imports, - domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host && swagger.basePath) ? swagger.schemes[0] + '://' + swagger.host + swagger.basePath.replace(/\/+$/g,'') : '', + domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host && swagger.basePath) ? `${swagger.schemes[0]}://${swagger.host}${swagger.basePath.replace(/\/+$/g,'')}` : '', methods: [], definitions: [] }; - _.forEach(swagger.paths, function(api, path){ - var globalParams = []; - /** - * @param {Object} op - meta data for the request - * @param {string} m - HTTP method name - eg: 'get', 'post', 'put', 'delete' - */ - _.forEach(api, function(op, m){ + + for (const [path, api] of Object.entries(swagger.paths)) { + let globalParams = []; + + for (const [m, op] of Object.entries(api)) { if(m.toLowerCase() === 'parameters') { globalParams = op; } - }); - _.forEach(api, function(op, m){ - var M = m.toUpperCase(); - if(M === '' || authorizedMethods.indexOf(M) === -1) { - return; + } + + for (const [m, op] of Object.entries(api)) { + const M = m.toUpperCase(); + if(M === '' || !authorizedMethods.includes(M)) { + continue; } - var secureTypes = []; + const secureTypes = []; if(swagger.securityDefinitions !== undefined || op.security !== undefined) { - var mergedSecurity = _.merge([], swagger.security, op.security).map(function(security){ - return Object.keys(security); - }); + const mergedSecurity = _.merge([], swagger.security, op.security).map(security => Object.keys(security)); if(swagger.securityDefinitions) { - for(var sk in swagger.securityDefinitions) { - if(mergedSecurity.join(',').indexOf(sk) !== -1){ + for(const sk in swagger.securityDefinitions) { + if(mergedSecurity.join(',').includes(sk)){ secureTypes.push(swagger.securityDefinitions[sk].type); } } } } - var methodName = (op.operationId ? normalizeName(op.operationId) : getPathToMethodName(opts, m, path)); + let methodName = (op.operationId ? normalizeName(op.operationId) : getPathToMethodName(opts, m, path)); // Make sure the method name is unique - if(methods.indexOf(methodName) !== -1) { - var i = 1; + if(methods.includes(methodName)) { + let i = 1; while(true) { - if(methods.indexOf(methodName + '_' + i) !== -1) { + if(methods.includes(`${methodName}_${i}`)) { i++; } else { - methodName = methodName + '_' + i; + methodName = `${methodName}_${i}`; break; } } } methods.push(methodName); - var method = { - path: path, + const method = { + path, className: opts.className, - methodName: methodName, + methodName, method: M, isGET: M === 'GET', isPOST: M === 'POST', summary: op.description || op.summary, externalDocs: op.externalDocs, isSecure: swagger.security !== undefined || op.security !== undefined, - isSecureToken: secureTypes.indexOf('oauth2') !== -1, - isSecureApiKey: secureTypes.indexOf('apiKey') !== -1, - isSecureBasic: secureTypes.indexOf('basic') !== -1, + isSecureToken: secureTypes.includes('oauth2'), + isSecureApiKey: secureTypes.includes('apiKey'), + isSecureBasic: secureTypes.includes('basic'), parameters: [], hasParameters: false, headers: [] @@ -118,25 +112,22 @@ var getViewForSwagger2 = function(opts, type){ if(method.isSecure && method.isSecureBasic) { data.isSecureBasic = method.isSecureBasic; } - var produces = op.produces || swagger.produces; + const produces = op.produces || swagger.produces; if(produces) { method.headers.push({ name: 'Accept', - value: `'${produces.map(function(value) { return value; }).join(', ')}'`, + value: `'${produces.map(value => value).join(', ')}'`, }); } - var consumes = op.consumes || swagger.consumes; + const consumes = op.consumes || swagger.consumes; if(consumes) { - method.headers.push({name: 'Content-Type', value: '\'' + consumes + '\'' }); + method.headers.push({name: 'Content-Type', value: `'${consumes}'` }); } - var params = []; - if(_.isArray(op.parameters)) { - params = op.parameters; - } + let params = Array.isArray(op.parameters) ? op.parameters : []; params = params.concat(globalParams); - _.forEach(params, function(parameter) { + _.forEach(params, parameter => { //Ignore parameters which contain the x-exclude-from-bindings extension if(parameter['x-exclude-from-bindings'] === true) { return; @@ -147,8 +138,8 @@ var getViewForSwagger2 = function(opts, type){ if (parameter['x-proxy-header'] && !data.isNode) { return; } - if (_.isString(parameter.$ref)) { - var segments = parameter.$ref.split('/'); + if (typeof parameter.$ref === 'string') { + const segments = parameter.$ref.split('/'); parameter = swagger.parameters[segments.length === 1 ? segments[0] : segments[2] ]; } parameter.camelCaseName = _.camelCase(parameter.name); @@ -177,25 +168,24 @@ var getViewForSwagger2 = function(opts, type){ method.parameters.push(parameter); }); - var success = 0; method.isInlineType = false; - _.forEach(op.responses, function(val, key) { + _.forEach(op.responses, ({schema, description}, key) => { if (key.startsWith('2')) { - if (val.schema) { - method.methodTsType = ts.convertType(val.schema); - method.methodFlowType = flow.convertType(val.schema); + if (schema) { + method.methodTsType = ts.convertType(schema); + method.methodFlowType = flow.convertType(schema); method.isInlineType = true; } else { - method.methodResponse = val.description; + method.methodResponse = description; } } }); method.hasParameters = method.parameters.length > 0; data.methods.push(method); - }); - }); + } + } - _.forEach(swagger.definitions, function(definition, name){ + _.forEach(swagger.definitions, (definition, name) => { data.definitions.push({ name: type === 'flow' ? flow.sanitizeReservedWords(name) : name, description: definition.description, @@ -207,9 +197,9 @@ var getViewForSwagger2 = function(opts, type){ return data; }; -var getViewForSwagger1 = function(opts, type){ - var swagger = opts.swagger; - var data = { +const getViewForSwagger1 = (opts, type) => { + const swagger = opts.swagger; + const data = { isNode: type === 'node' || type === 'react', isES6: opts.isES6 || type === 'react', description: swagger.description, @@ -218,13 +208,13 @@ var getViewForSwagger1 = function(opts, type){ domain: swagger.basePath ? swagger.basePath : '', methods: [] }; - swagger.apis.forEach(function(api){ - api.operations.forEach(function(op){ + swagger.apis.forEach(({operations, path}) => { + operations.forEach(op => { if (op.method === 'OPTIONS') { return; } - var method = { - path: api.path, + const method = { + path: path, className: opts.className, methodName: op.nickname, method: op.method, @@ -236,15 +226,15 @@ var getViewForSwagger1 = function(opts, type){ }; if(op.produces) { - var headers = []; + const headers = []; headers.value = []; headers.name = 'Accept'; - headers.value.push(op.produces.map(function(value) { return '\'' + value + '\''; }).join(', ')); + headers.value.push(op.produces.map(value => `'${value}'`).join(', ')); method.headers.push(headers); } op.parameters = op.parameters ? op.parameters : []; - op.parameters.forEach(function(parameter) { + op.parameters.forEach(parameter => { parameter.camelCaseName = _.camelCase(parameter.name); if(parameter.enum && parameter.enum.length === 1) { parameter.isSingleton = true; @@ -272,9 +262,9 @@ var getViewForSwagger1 = function(opts, type){ return data; }; -var getCode = function(opts, type) { +const getCode = (opts, type) => { // For Swagger Specification version 2.0 value of field 'swagger' must be a string '2.0' - var data = opts.swagger.swagger === '2.0' ? getViewForSwagger2(opts, type) : getViewForSwagger1(opts, type); + const data = opts.swagger.swagger === '2.0' ? getViewForSwagger2(opts, type) : getViewForSwagger1(opts, type); if (type === 'custom') { if (!_.isObject(opts.template) || !_.isString(opts.template.class) || !_.isString(opts.template.method)) { throw new Error('Unprovided custom template. Please use the following template: template: { class: "...", method: "...", request: "..." }'); @@ -283,13 +273,13 @@ var getCode = function(opts, type) { if (!_.isObject(opts.template)) { opts.template = {}; } - var templates = __dirname + '/../templates/'; - opts.template.class = opts.template.class || fs.readFileSync(templates + type + '-class.mustache', 'utf-8'); - opts.template.method = opts.template.method || fs.readFileSync(templates + (_.includes(['flow', 'typescript'], type) ? type + '-' : '') + 'method.mustache', 'utf-8'); + const templates = `${__dirname}/../templates/`; + opts.template.class = opts.template.class || fs.readFileSync(`${templates + type}-class.mustache`, 'utf-8'); + opts.template.method = opts.template.method || fs.readFileSync(`${templates + (_.includes(['flow', 'typescript'], type) ? `${type}-` : '')}method.mustache`, 'utf-8'); if(type === 'typescript') { - opts.template.type = opts.template.type || fs.readFileSync(templates + 'type.mustache', 'utf-8'); + opts.template.type = opts.template.type || fs.readFileSync(`${templates}type.mustache`, 'utf-8'); } else if (type === 'flow') { - opts.template.type = opts.template.type || fs.readFileSync(templates + 'flow-type.mustache', 'utf-8'); + opts.template.type = opts.template.type || fs.readFileSync(`${templates}flow-type.mustache`, 'utf-8'); } } @@ -297,8 +287,8 @@ var getCode = function(opts, type) { _.assign(data, opts.mustache); } - var source = Mustache.render(opts.template.class, data, opts.template); - var lintOptions = { + const source = Mustache.render(opts.template.class, data, opts.template); + const lintOptions = { node: type === 'node' || type === 'custom', browser: type === 'angular' || type === 'custom' || type === 'react', undef: true, @@ -317,9 +307,9 @@ var getCode = function(opts, type) { if (opts.lint === undefined || opts.lint === true) { lint(source, lintOptions); - lint.errors.forEach(function(error) { - if (error.code[0] === 'E') { - throw new Error(error.reason + ' in ' + error.evidence + ' (' + error.code + ')'); + lint.errors.forEach(({code, reason, evidence}) => { + if (code[0] === 'E') { + throw new Error(`${reason} in ${evidence} (${code})`); } }); } @@ -337,19 +327,19 @@ exports.CodeGen = { } return getCode(opts, 'typescript'); }, - getAngularCode: function(opts){ + getAngularCode(opts) { return getCode(opts, 'angular'); }, - getNodeCode: function(opts){ + getNodeCode(opts) { return getCode(opts, 'node'); }, - getReactCode: function(opts){ + getReactCode(opts) { return getCode(opts, 'react'); }, - getFlowCode: function(opts) { + getFlowCode(opts) { return getCode(opts, 'flow'); }, - getCustomCode: function(opts){ + getCustomCode(opts) { return getCode(opts, 'custom'); } }; diff --git a/lib/flow.js b/lib/flow.js index f818eda7..d79612b8 100644 --- a/lib/flow.js +++ b/lib/flow.js @@ -1,6 +1,6 @@ 'use strict'; -var _ = require('lodash'); +const _ = require('lodash'); /** * Recursively converts a swagger type description into a flow type, i.e., a model for our mustache @@ -12,19 +12,19 @@ var _ = require('lodash'); * @returns a recursive structure representing the type, which can be used as a template model. */ -var reservedWords = [ - "abstract","arguments","await","boolean","break","byte","case","catch","char", - "class","const","continue","debugger","default","delete","do","double","else", - "enum","eval","export","extends","false","final","finally","float","for", - "function","goto","if","implements","import","in","instanceof","int","interface", - "let","long","native","new","null","package","private","protected","public","return", - "short","static","super","switch","synchronized","this","throw","throws","transient", - "true","try","typeof","var","void","volatile","while","with","yield" +const reservedWords = [ + 'abstract','arguments','await','boolean','break','byte','case','catch','char', + 'class','const','continue','debugger','default','delete','do','double','else', + 'enum','eval','export','extends','false','final','finally','float','for', + 'function','goto','if','implements','import','in','instanceof','int','interface', + 'let','long','native','new','null','package','private','protected','public','return', + 'short','static','super','switch','synchronized','this','throw','throws','transient', + 'true','try','typeof','var','void','volatile','while','with','yield' ]; function sanitizeReservedWords(word) { - if (_.includes(reservedWords, word)) { - return word + '_type'; + if (reservedWords.includes(word)) { + return `${word}_type`; } return word; } @@ -34,7 +34,7 @@ function getNameFromRef(ref) { } function convertType(swaggerType, swagger) { - var typespec = { + const typespec = { description: swaggerType.description, simpleFlowType: undefined, isObject: false, @@ -45,7 +45,7 @@ function convertType(swaggerType, swagger) { return convertType(swaggerType.schema); } - if (_.isString(swaggerType.$ref)) { + if (typeof swaggerType.$ref === 'string') { typespec.simpleFlowType = getNameFromRef(swaggerType.$ref); } else if (swaggerType.hasOwnProperty('enum')) { typespec.simpleFlowType = swaggerType.enum.map(JSON.stringify).join(' | '); @@ -70,28 +70,28 @@ function convertType(swaggerType, swagger) { typespec.isObject = true; typespec.properties = []; if (swaggerType.allOf) { - _.forEach(swaggerType.allOf, function (ref) { + _.forEach(swaggerType.allOf, ref => { if(ref.$ref) { - var name = getNameFromRef(ref.$ref); - _.forEach(swagger.definitions, function (definition, definitionName) { + const name = getNameFromRef(ref.$ref); + _.forEach(swagger.definitions, (definition, definitionName) => { if (definitionName === name) { - var property = convertType(definition, swagger); + const property = convertType(definition, swagger); Array.prototype.push.apply(typespec.properties, property.properties); } }); } else { - var property = convertType(ref); + const property = convertType(ref); Array.prototype.push.apply(typespec.properties, property.properties); } }); } - _.forEach(swaggerType.properties, function (propertyType, propertyName) { - var property = convertType(propertyType); + _.forEach(swaggerType.properties, (propertyType, propertyName) => { + const property = convertType(propertyType); property.name = propertyName; property.optional = true; - if (swaggerType.required && swaggerType.required.indexOf(propertyName) !== -1) { + if (swaggerType.required && swaggerType.required.includes(propertyName)) { property.optional = false; } diff --git a/lib/typescript.js b/lib/typescript.js index b6c5a844..bfa1210f 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1,6 +1,6 @@ 'use strict'; -var _ = require('lodash'); +const _ = require('lodash'); /** * Recursively converts a swagger type description into a typescript type, i.e., a model for our mustache @@ -13,7 +13,7 @@ var _ = require('lodash'); */ function convertType(swaggerType, swagger) { - var typespec = { description: swaggerType.description, isEnum: false }; + const typespec = { description: swaggerType.description, isEnum: false }; if (swaggerType.hasOwnProperty('schema')) { return convertType(swaggerType.schema); @@ -21,7 +21,7 @@ function convertType(swaggerType, swagger) { typespec.tsType = 'ref'; typespec.target = swaggerType.$ref.substring(swaggerType.$ref.lastIndexOf('/') + 1); } else if (swaggerType.hasOwnProperty('enum')) { - typespec.tsType = swaggerType.enum.map(function(str) { return JSON.stringify(str); }).join(' | '); + typespec.tsType = swaggerType.enum.map(str => JSON.stringify(str)).join(' | '); typespec.isAtomic = true; typespec.isEnum = true; } else if (swaggerType.type === 'string') { @@ -41,29 +41,29 @@ function convertType(swaggerType, swagger) { typespec.tsType = 'object'; typespec.properties = []; if (swaggerType.allOf) { - _.forEach(swaggerType.allOf, function (ref) { + _.forEach(swaggerType.allOf, ref => { if(ref.$ref) { - var refSegments = ref.$ref.split('/'); - var name = refSegments[refSegments.length - 1]; - _.forEach(swagger.definitions, function (definition, definitionName) { + const refSegments = ref.$ref.split('/'); + const name = refSegments[refSegments.length - 1]; + _.forEach(swagger.definitions, (definition, definitionName) => { if (definitionName === name) { - var property = convertType(definition, swagger); + const property = convertType(definition, swagger); Array.prototype.push.apply(typespec.properties, property.properties); } }); } else { - var property = convertType(ref); + const property = convertType(ref); Array.prototype.push.apply(typespec.properties, property.properties); } }); } - _.forEach(swaggerType.properties, function (propertyType, propertyName) { - var property = convertType(propertyType); + _.forEach(swaggerType.properties, (propertyType, propertyName) => { + const property = convertType(propertyType); property.name = propertyName; property.optional = true; - if (swaggerType.required && swaggerType.required.indexOf(propertyName) !== -1) { + if (swaggerType.required && swaggerType.required.includes(propertyName)) { property.optional = false; } @@ -79,7 +79,7 @@ function convertType(swaggerType, swagger) { typespec.isRef = typespec.tsType === 'ref'; typespec.isObject = typespec.tsType === 'object'; typespec.isArray = typespec.tsType === 'array'; - typespec.isAtomic = typespec.isAtomic || _.includes(['string', 'number', 'boolean', 'any'], typespec.tsType); + typespec.isAtomic = typespec.isAtomic || ['string', 'number', 'boolean', 'any'].includes(typespec.tsType); return typespec; } diff --git a/tests/generation.js b/tests/generation.js index bbbd636e..ccfeb4a4 100644 --- a/tests/generation.js +++ b/tests/generation.js @@ -10,38 +10,38 @@ var tmp = require('tmp'); var CodeGen = require('../lib/codegen').CodeGen; function compileString(testName, input) { - var tmpDir = tmp.dirSync({ + const tmpDir = tmp.dirSync({ dir: './', unsafeCleanup: true, keep: true }); - var tmpFile = tmp.fileSync({ + const tmpFile = tmp.fileSync({ postfix: '.ts', dir: tmpDir.name, keep: true }); fs.writeFileSync(tmpFile.fd, input); - var program = ts.createProgram([tmpFile.name], { + const program = ts.createProgram([tmpFile.name], { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2016, // Makes promises resolve moduleResolution: ts.ModuleResolutionKind.NodeJs // ensure we can use node_modules }); - var emitResult = program.emit(); + const emitResult = program.emit(); - var allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); - allDiagnostics.forEach(function(diagnostic) { - var lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); - var line = lineAndCharacter.line; - var character = lineAndCharacter.character; - var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); - var outputLine = diagnostic.file.text.split('\n')[line]; - console.log('\n' + testName + ': (' + (line + 1) + ',' + (character + 1) + '): ' + message); - console.log(' ERROR line: ' + outputLine.trim()); + allDiagnostics.forEach(({file, start, messageText}) => { + const lineAndCharacter = file.getLineAndCharacterOfPosition(start); + const line = lineAndCharacter.line; + const character = lineAndCharacter.character; + const message = ts.flattenDiagnosticMessageText(messageText, '\n'); + const outputLine = file.text.split('\n')[line]; + console.log(`\n${testName}: (${line + 1},${character + 1}): ${message}`); + console.log(` ERROR line: ${outputLine.trim()}`); }); - var errorsSeen = allDiagnostics.length !== 0; + const errorsSeen = allDiagnostics.length !== 0; if (errorsSeen) { console.log(' ERRORS seen, generated code preserved in: ' + tmpFile.name); } else { @@ -51,33 +51,33 @@ function compileString(testName, input) { return !errorsSeen; } -var batch = {}; -var list = ffs.readdirSync('tests/apis'); -list.forEach(function(file){ - file = 'tests/apis/' + file; - batch[file] = function(){ - var swagger = JSON.parse(fs.readFileSync(file, 'UTF-8')); - var result = CodeGen.getNodeCode({ +const batch = {}; +const list = ffs.readdirSync('tests/apis'); +list.forEach(file => { + file = `tests/apis/${file}`; + batch[file] = () => { + const swagger = JSON.parse(fs.readFileSync(file, 'UTF-8')); + let result = CodeGen.getNodeCode({ className: 'Test', - swagger: swagger + swagger }); assert(typeof(result), 'string'); result = CodeGen.getReactCode({ moduleName: 'Test', className: 'Test', - swagger: swagger + swagger }); assert(typeof(result), 'string'); result = CodeGen.getAngularCode({ moduleName: 'Test', className: 'Test', - swagger: swagger + swagger }); assert(typeof(result), 'string'); result = CodeGen.getAngularCode({ moduleName: 'Test', className: 'Test', - swagger: swagger, + swagger, lint: false, beautify: false }); @@ -87,7 +87,7 @@ list.forEach(function(file){ result = CodeGen.getTypescriptCode({ moduleName: 'Test', className: 'Test', - swagger: swagger, + swagger, lint: false }); assert(compileString('typescript generation: ' + file, result), 'typescript compilation failed'); @@ -96,7 +96,7 @@ list.forEach(function(file){ result = CodeGen.getCustomCode({ moduleName: 'Test', className: 'Test', - swagger: swagger, + swagger, template: { class: fs.readFileSync(__dirname + '/../templates/angular-class.mustache', 'utf-8'), method: fs.readFileSync(__dirname + '/../templates/method.mustache', 'utf-8')