Coder Social home page Coder Social logo

swagger-axios-codegen's Introduction

swagger-axios-codegen

A swagger client uses axios and typescript

NpmVersionnpm open issues

< v0.16 require node > v10.0.0

>= v0.16 require node >= v16

it will always resolve axios.response.data or reject axios.error with Promise

support other similar to axios library, for example Fly.js, required setting ISwaggerOptions.useCustomerRequestInstance = true

the es6 version is generated by calling typescript

Welcome PRs and commit issue

By the way. you can support this repo via Star star sta st s... ⭐️ ⭐️ ⭐️ ⭐️ ⭐️

Get Started

  yarn add swagger-axios-codegen
export interface ISwaggerOptions {
  serviceNameSuffix?: string
  enumNamePrefix?: string
  methodNameMode?: 'operationId' | 'path' | 'shortOperationId' | ((reqProps: IRequestMethod) => string)
  classNameMode?: 'parentPath' | 'normal' | ((path: string, method: string, reqProps:IRequestMethod) => string)
  /** only effect classNameMode='parentPath' */
  pathClassNameDefaultName?: string
  outputDir?: string
  fileName?: string
  remoteUrl?: string
  source?: any
  useStaticMethod?: boolean | undefined
  useCustomerRequestInstance?: boolean | undefined
  include?: Array<string | IInclude>
  /** include types which are not included during the filtering **/
  includeTypes?: Array<string>
  format?: (s: string) => string
  /** match with tsconfig */
  strictNullChecks?: boolean | undefined
  /** definition Class mode */
  modelMode?: 'class' | 'interface'
  /** use class-transformer to transform the results */
  useClassTransformer?: boolean
  /** force the specified swagger or openAPI version, */
  openApi?: string | undefined
  /** extend file url. It will be inserted in front of the service method */
  extendDefinitionFile?: string | undefined
  /** mark generic type */
  extendGenericType?: string[] | undefined
  /** generate validation model (class model mode only) */
  generateValidationModel?: boolean
  /** split request service.  Can't use with sharedServiceOptions*/
  multipleFileMode?: boolean | undefined
  /** url prefix filter*/
  urlFilters?: string[] | null | undefined
  /** shared service options to multiple service. Can't use with MultipleFileMode */
  sharedServiceOptions?: boolean | undefined
  /** use parameters in header or not*/
  useHeaderParameters?: boolean
}

const defaultOptions: ISwaggerOptions = {
  serviceNameSuffix: 'Service',
  enumNamePrefix: 'Enum',
  methodNameMode: 'operationId',
  classNameMode: 'normal',
  PathClassNameDefaultName: 'Global',
  outputDir: './service',
  fileName: 'index.ts',
  useStaticMethod: true,
  useCustomerRequestInstance: false,
  include: [],
  strictNullChecks: true,
  /** definition Class mode ,auto use interface mode to streamlined code*/
  modelMode?: 'interface',
  useClassTransformer: false
}

use local swagger api json

const { codegen } = require('swagger-axios-codegen')
codegen({
  methodNameMode: 'operationId',
  source: require('./swagger.json')
})

use remote swagger api json

const { codegen } = require('swagger-axios-codegen')
codegen({
  methodNameMode: 'operationId',
  remoteUrl:'You remote Url'
})

use static method

codegen({
    methodNameMode: 'operationId',
    remoteUrl: 'http://localhost:22742/swagger/v1/swagger.json',
    outputDir: '.',
    useStaticMethod: true
});

before

import { UserService } from './service'
const userService = new UserService()
await userService.GetAll();

after

import { UserService } from './service'

await UserService.GetAll();

use custom axios.instance

import axios from 'axios'
import { serviceOptions } from './service'
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

serviceOptions.axios = instance

use other library

import YourLib from '<Your lib>'
import { serviceOptions } from './service'

serviceOptions.axios = YourLib

filter service and method

fliter by multimatch using 'include' setting

codegen({
  methodNameMode: 'path',
  source: require('../swagger.json'),
  outputDir: './swagger/services',
  include: [
    '*',
    // 'Products*',
    '!Products',
    { 'User': ['*', '!history'] },
  ]
})

If you are using special characters in your service name (which is the first tag) you must assume they have been escaped.

For example the service names are MyApp.FirstModule.Products, MyApp.FirstModule.Customers, MyApp.SecondModule.Orders:

// API
"paths": {
  "/Products/Get": {
    "post": {
      "tags": [
        "MyApp.FirstModule.Products"
      ],
      "operationId": "Get",
// Codegen config
codegen({
  methodNameMode: 'path',
  source: require('../swagger.json'),
  outputDir: './swagger/services',
  include: ['MyAppFirstModule*'] // Only Products and Customers will be included. As you can see dots are escaped being contract names.
})

use class transformer to transform results

This is helpful if you want to transform dates to real date objects. Swagger can define string formats for different types. Two if these formats are date and date-time

If a class-transformer is enabled and a format is set on a string, the result string will be transformed to a Date instance

// swagger.json

{
  "ObjectWithDate": {
    "type": "object",
    "properties": {
      "date": {
        "type": "string",
        "format": "date-time"
      }
    }
  }
}
const { codegen } = require('swagger-axios-codegen')
codegen({
  methodNameMode: 'operationId',
  source:require('./swagger.json'),
  useClassTransformer: true,
})

Resulting class:

export class ObjectWithDate {
  @Expose()
  @Type(() => Date)
  public date: Date;
}

The service method will transform the json response and return an instance of this class

use validation model

codegen({
    ...
    modelMode: 'class',
    generateValidationModel: true
});

The option above among with class model mode allows to render the model validation rules. The result of this will be as follows:

export class FooFormVm {
  'name'?: string;
  'description'?: string;
 
  constructor(data: undefined | any = {}) {
    this['name'] = data['name'];
    this['description'] = data['description'];
  }
 
  public static validationModel = {
    name: { required: true, maxLength: 50 },
    description: { maxLength: 250 },
  };
}

So you can use the validation model in your application:

function isRequired(vm: any, fieldName: string): boolean {
  return (vm && vm[fieldName] && vm[fieldName].required === true);
}
function maxLength(vm: any, fieldName: string): number {
  return (vm && vm[fieldName] && vm[fieldName].maxLength ? vm[fieldName].maxLength : 4000);
}

Now you can use the functions

var required = isRequired(FooFormVm.validationModel, 'name');
var maxLength = maxLength(FooFormVm.validationModel, 'description');

At the moment there are only two rules are supported - required and maxLength.

Some Solution

1.Reference parameters

see in #53, use package json-schema-ref-parser

2.With Microservice Gateway

const {codegen} = require('swagger-axios-codegen')
const axios = require('axios')
// host 地址
const host = 'http://your-host-name'

// 
const modules = [
  ...
]

axios.get(`${host}/swagger-resources`).then(async ({data}) => {
  console.warn('code', host)
  for (let n of data) {
    if (modules.includes(n.name)) {
      try {
        await codegen({
          remoteUrl: `${host}${n.url}`,
          methodNameMode: 'operationId',
          modelMode: 'interface',
          strictNullChecks: false,
          outputDir: './services',
          fileName: `${n.name}.ts`,
          sharedServiceOptions: true,
          extendDefinitionFile: './customerDefinition.ts',
        })
      } catch (e) {
        console.log(`${n.name} service error`, e.message)
      }
    }
  }
})

swagger-axios-codegen's People

Contributors

arkraft avatar bpmct avatar callmeberzerker avatar ctrl-q avatar dependabot[bot] avatar domenikjones avatar fairking avatar hexi1997 avatar italodeandra avatar klimentru1986 avatar kt81 avatar lamuertepeluda avatar manweill avatar martinloeper avatar maxim-mazurok avatar mingoes avatar morbalint avatar nibytes avatar oemer-aran avatar popravkoalex avatar ronangaillard avatar sandragg avatar tran2 avatar vcing avatar vilyus avatar wangminghua111 avatar will7200 avatar wizofaus avatar xxbld avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

swagger-axios-codegen's Issues

Make responseType configurable

Currently you can't configure the responseType, which is needed in some special cases (e.g. when the api is returning a PDF file you need to set responseType to arraybuffer).

I already fixed this in PR #40

HEAD/GET methods with same OperationId cause invalid typescript

For the swagger.json:

"/api/ping":{"get":{"tags":["HealthCheck"],"operationId":"Ping","consumes":[],"produces":[],"parameters":[],"responses":{"200":{"description":"Success"}}},"head":{"tags":["HealthCheck"],"operationId":"Ping","consumes":[],"produces":[],"parameters":[],"responses":{"200":{"description":"Success"}}}}

I get typescript output that tries to define the ping function twice for the same HealthCheckService class, which fails to compile.
If I change the operationId for one of them (e.g. "PingHead"), it generates valid output but at the moment that's out of my control other than doing pre-processing on the json before running codegen.

Validation attributes

Would like to see something to be able to generate validation attributes among with model classes.
It would be really cool.

My view model looks like this:
image

I got my api like this:
image

I am thinking about to implement client validation using vuelidate or VeeValidate

Is there any way to somehow translate model attributes using swagger-axios-codegen and use them in validation?
Any ideas?

can't support Generics

like

	"ClientResult«AuthUserDTO»": {
		"type": "object",
		"properties": {
			"data": {
				"$ref": "#/definitions/AuthUserDTO"
			},
			"msg": {
				"type": "string"
			},
			"success": {
				"type": "boolean"
			}
		},
		"title": "ClientResult«AuthUserDTO»"
	}

TypeError: Cannot read property 'schemas' of undefined

$ npm run gen

> [email protected] gen C:\Dev\[App]
> node ./codegen.js

openApi version: 3.0.1
isV3 true
(node:9700) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'schemas' of undefined
    at Object.componentsCodegen (C:\Dev\[App]\node_modules\swagger-axios-codegen\dist\componentsCodegen\index.js:9:53)
    at codegen (C:\Dev\[App]\node_modules\swagger-axios-codegen\dist\index.js:68:58)
    at Object.<anonymous> (C:\Dev\[App]\codegen.js:2:1)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11
(node:9700) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

With the following swagger.json output from Swashbuckle:

{
  "openapi": "3.0.1",
  "info": {
    "title": "API",
    "description": "Internal API",
    "version": "v0"
  },
  "paths": {
    "/api/v0/accounts": {
      "get": {
        "tags": [
          "Account"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/addresses": {
      "get": {
        "tags": [
          "Address"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/conferences": {
      "get": {
        "tags": [
          "Conference"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/exhibitors": {
      "get": {
        "tags": [
          "ExhibitorContoller"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/facilities": {
      "get": {
        "tags": [
          "Facilities"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/functions": {
      "get": {
        "tags": [
          "Function"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/function-resources": {
      "get": {
        "tags": [
          "FunctionResource"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/function-resource-types": {
      "get": {
        "tags": [
          "FunctionResourceType"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/notes": {
      "get": {
        "tags": [
          "Note"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/roles": {
      "get": {
        "tags": [
          "Role"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/roomes": {
      "get": {
        "tags": [
          "Room"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/room-styles": {
      "get": {
        "tags": [
          "RoomStyle"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/sponsors": {
      "get": {
        "tags": [
          "Sponsor"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/unit-of-measures": {
      "get": {
        "tags": [
          "UnitOfMeasure"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/users": {
      "get": {
        "tags": [
          "User"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    }
  }
}

duplicate methods

If path has several method like, '/orders': { get, post, put, delete}, it will generate duplicate method, perhaps we need to add the HTTP method in the class method.

UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object

Seems to barf on the empty components:{} section, I removed it manually and it still errors on #59

$ npm run gen

> [email protected] gen C:\Dev\[App]
> node ./codegen.js

openApi version: 3.0.1
isV3 true
(node:15668) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.entries (<anonymous>)
    at Object.componentsCodegen (C:\Dev\[App]\node_modules\swagger-axios-codegen\dist\componentsCodegen\index.js:9:33)
    at codegen (C:\Dev\[App]\node_modules\swagger-axios-codegen\dist\index.js:68:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:15668) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise 
which was not handled with .catch(). (rejection id: 1)
(node:15668) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero 
exit code.

With the following swagger.json output from Swashbuckle:

{
  "openapi": "3.0.1",
  "info": {
    "title": "API",
    "description": "Internal API",
    "version": "v0"
  },
  "paths": {
    "/api/v0/accounts": {
      "get": {
        "tags": [
          "Account"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/addresses": {
      "get": {
        "tags": [
          "Address"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/conferences": {
      "get": {
        "tags": [
          "Conference"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/exhibitors": {
      "get": {
        "tags": [
          "ExhibitorContoller"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/facilities": {
      "get": {
        "tags": [
          "Facilities"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/functions": {
      "get": {
        "tags": [
          "Function"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/function-resources": {
      "get": {
        "tags": [
          "FunctionResource"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/function-resource-types": {
      "get": {
        "tags": [
          "FunctionResourceType"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/notes": {
      "get": {
        "tags": [
          "Note"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/roles": {
      "get": {
        "tags": [
          "Role"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/roomes": {
      "get": {
        "tags": [
          "Room"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/room-styles": {
      "get": {
        "tags": [
          "RoomStyle"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/sponsors": {
      "get": {
        "tags": [
          "Sponsor"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/unit-of-measures": {
      "get": {
        "tags": [
          "UnitOfMeasure"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
    "/api/v0/users": {
      "get": {
        "tags": [
          "User"
        ],
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    }
  },
  "components": { }
}

Need normalize class name and perhaps other names

error { SyntaxError: '{' expected. (2376:17)
2374 |
2375 |

2376 | export class x-any {
| ^
2377 |
2378 |
2379 |
at e (/Users/z/Projects/Node/turtle/node_modules/prettier/parser-typescript.js:1:267)
at Object.parse (/Users/z/Projects/Node/turtle/node_modules/prettier/parser-typescript.js:1:2172547)
at Object.parse$2 [as parse] (/Users/z/Projects/Node/turtle/node_modules/prettier/index.js:10639:19)
at coreFormat (/Users/z/Projects/Node/turtle/node_modules/prettier/index.js:13856:23)
at format (/Users/z/Projects/Node/turtle/node_modules/prettier/index.js:14115:73)
at formatWithCursor (/Users/z/Projects/Node/turtle/node_modules/prettier/index.js:14131:12)
at /Users/z/Projects/Node/turtle/node_modules/prettier/index.js:42399:15
at Object.format (/Users/z/Projects/Node/turtle/node_modules/prettier/index.js:42418:12)
at format (/Users/z/Projects/Node/turtle/node_modules/swagger-axios-codegen/dist/index.js:188:31)
at codegen (/Users/z/Projects/Node/turtle/node_modules/swagger-axios-codegen/dist/index.js:162:72)
loc: { start: { line: 2376, column: 17 } },
codeFrame:
'\u001b[0m \u001b[90m 2374 | \u001b[39m \u001b[0m\n\u001b[0m \u001b[90m 2375 | \u001b[39m\u001b[0m\n\u001b[0m\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 2376 | \u001b[39m \u001b[36mexport\u001b[39m \u001b[36mclass\u001b[39m x\u001b[33m-\u001b[39many {\u001b[0m\n\u001b[0m \u001b[90m | \u001b[39m \u001b[31m\u001b[1m^\u001b[22m\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 2377 | \u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 2378 | \u001b[39m \u001b[0m\n\u001b[0m \u001b[90m 2379 | \u001b[39m\u001b[0m' }
finish: 692.269ms
✨ Done in 4.44s.

Unsupported type definition

Hi,
consider following swagger example:

{
    ...
    definitions: {
        Abc: {
            properties: {
                id: {
                type: "string"
            }
        },
        ArrayOfAbc: {
            type: "array",
            items: {
                $ref: "#/definitions/Abc"
            }
        }
    },
    ...
}

Method createDefinitionClass in definitionCodegen.ts expects all types have property properties, but array doesn't. Generation with such swagger file fails with error:

(node:16624) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.entries (<anonymous>)
    at createDefinitionClass (C:\Data\node\logio-promo-pricing\node_modules\swagger-axios-codegen\dist\definitionCodegen.js:65:39)
    at Object.definitionsCodeGen (C:\Data\node\logio-promo-pricing\node_modules\swagger-axios-codegen\dist\definitionCodegen.js:101:34)
    at codegen (C:\Data\node\logio-promo-pricing\node_modules\swagger-axios-codegen\dist\index.js:56:38)
    at Object.<anonymous> (C:\Data\node\logio-promo-pricing\packages\data-pump\src\swagger\codegen.js:3:1)
    at Module._compile (module.js:649:14)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

An idea for filtering request method

An idea for filtering build methods, that filter requests by simply using app or web pages or other specific clients.
In .NET Server like this, add a new attribute

.NET

Controller

        [AttrName]
        public async Task Post(string url)
        {
              ...
        }

SwaggerFilter

public class SwaggerFilterHelper : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var action = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;

            operation.OperationId = action.ActionName;
            var attr = context.ApiDescription.CustomAttributes()
                .OfType<YourAttrName>()
                .FirstOrDefault();
            if (attr != null)
            {
                operation.Extensions.Add("x-tag","YourAttrName");
            }
        }

Swagger Spec

"/api/abp/api-definition": {
      "Post": {
        "tags": [
          "api-definition"
        ],
        "responses": {
          "200": {
            "description": "Success",
            "content": {
              "text/plain": {
                "schema": {
                  "$ref": "#/components/schemas/ApplicationApiDescriptionModel"
                }
              },
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApplicationApiDescriptionModel"
                }
              },
              "text/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApplicationApiDescriptionModel"
                }
              }
            }
          }
        }
      },
     "x-tag":"YourAttrName"
    }

Wrong replace params in PUT requests

Hi, first of all thank you for this repo which helped us a lot with our project. Today, I encountered error when using generated service for PUT requests.

When Swagger URL for PUT includes an object like this,

let url = '/crawler/v1/mapper/{mapper.id}';

replace string for the URL is generated as
replace('{mapperId}', params['mapperId'] + '');

instead of
replace('{mapper.id}', params['mapperId'] + '');

so the URL string is not updated with the variable and PUT requests do not work

yarn : error

when i exec yarn add swagger-axios-codegen
show this error

internal/modules/cjs/loader.js:796
    throw err;
    ^

Error: Cannot find module 'D:\node_modules\npm\bin\npm-cli.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
    at Function.Module._load (internal/modules/cjs/loader.js:686:27)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
error Command failed with exit code 1.

swagger3 requestBody schema

Hi

Are you planing to support requestBody schema in the generated code? As far as I can see, there's only a data assignment to null (let data = null), but it's not possible to pass actual data to the generated service methods.

Thx

Translates boolean parameter type to any

First of all, thank you for this codegen and the time you put into it.

I have a problem converting boolean parameter types. They are correctly defined as boolean in the swagger.json file, but the generated client replaces them with any:

      "get": {
        "summary": "Notifications",
        "operationId": "getNotifications",
        "parameters": [
          {
            "type": "boolean",
            "name": "groups",
            "required": true,
            "in": "query"
          },
          {
            "type": "boolean",
            "name": "onlyUnread",
            "required": true,
            "in": "query"
          }
        ],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/definitions/NotificationDto"
              }
            }
          },
        },
        "tags": [
          "Notification"
        ],
        "security": [
          {
            "oauth2": []
          }
        ],
        "produces": [
          "application/json"
        ],
        "consumes": [
          "application/json"
        ]
      }

and this is the generated method:

  /**
   * Notifications
   */
  getNotifications(
    params: {
      /**  */
      groups: any;
      /**  */
      onlyUnread: any;
    } = {} as any,
    options: IRequestOptions = {},
  ): Promise<NotificationDto[]> {
    return new Promise((resolve, reject) => {
      const configs: IRequestConfig = { ...options, method: 'get' };
      configs.headers = {
        ...options.headers,
        'Content-Type': 'application/json',
      };
      const url = '/api/notifications';

      configs.url = url;
      configs.params = { groups: params.groups, onlyUnread: params.onlyUnread };
      const data = null;

      configs.data = data;
      axios(configs)
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

The notifications parameters for groups and onlyUnread are of type any. It works for strings and numbers as far as i can tell

Cannot convert undefined or null to object

Error appears in swagger-axios-codegen/dist/definitionCodegen/createDefinitionClass.js:19:39

when:
if in swagger output I have definition without properties. If definition contains even empty properties it works

example:

"definitions": {
    // triggers error
    "ItemId": {
      "type": "object"
    },
    // works
    "ItemId": {
      "type": "object",
      "properties": {}
    },
}

sulution
change:
const propertiesEntities = Object.entries(properties);
to:
const propertiesEntities = Object.entries(properties || {});

or check if properies are undefines then don't even try to get entries.

Cannot read property 'imports' of undefined

Hi,

I think you should add a check at this line of code https://github.com/Manweill/swagger-axios-codegen/blob/master/src/requestCodegen/index.ts#L54 and line above, like

if(refResponseType && parsedParameters && Array.isArray(parsedParameters.imports)){
  parsedParameters.imports.push(responseType)
}

I get this error

error TypeError: Cannot read property 'imports' of undefined
    at Object.requestCodegen (/Users/vito/Development/JavaScript/VISCA/swagger-codegen/node_modules/swagger-axios-codegen/dist/requestCodegen/index.js:40:34)
    at codegen (/Users/vito/Development/JavaScript/VISCA/swagger-codegen/node_modules/swagger-axios-codegen/dist/index.js:140:45)
    at generateApi (/Users/vito/Development/JavaScript/VISCA/swagger-codegen/apigen.js:24:11)
    at process._tickCallback (internal/process/next_tick.js:68:7)

which is also swallowed, i.e. codegen() does not throw, but also does not generate the api.

Option to split generated code in multiple files

Hey guys, I just started using swagger-axios-codegen.

Are there any technical issues why you aren't splitting the generated code into multiple files spread over multiple folders? And may this be an option for future releases?

Trouble when generating with string type definitions

Hi!

I'm have trouble when generating with string type definitions.
Example of swagger.json:

{
  "swagger" : "2.0",
  "info" : {
    "version" : "1.0.0",
    "title" : "Test API"
  },
  "host" : "api.test.com",
  "basePath" : "/v1",
  "schemes" : [ "https" ],
  "produces" : [ "application/json" ],
  "paths" : {
  },
  "definitions" : {
    "ContractStatus" : {
      "type" : "string",
      "description" : "Enumeration of contract status",
      "enum" : [ "Placed", "Approved", "Started", "Closed" ]
    }
  }
}

Error:

(node:31783) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.entries (<anonymous>)
    at createDefinitionClass (/Users/damir/proj/node_modules/swagger-axios-codegen/dist/definitionCodegen.js:65:39)
    at Object.definitionsCodeGen (/Users/damir/proj/node_modules/swagger-axios-codegen/dist/definitionCodegen.js:101:34)
    at codegen (/Users/damir/proj/node_modules/swagger-axios-codegen/dist/index.js:56:38)
    at Object.<anonymous> (/Users/damir/proj/swag/codegen.js:3:1)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
(node:31783) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:31783) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Arrays of enum values

I have a swagger configuration where one attribute is an array of enum values (number). This enum is correctly translated into a type, but the property itself is not an array anymore. For example:

 features:
        type: array
        uniqueItems: true
        items:
          type: number
          enum:
            - 10
            - 11
            - 20
            - 30
            - 40
            - 50
            - 51
            - 61
            - 71
            - 72

creates the following enum type:

type StructureDtoFeatures = 10 | 11 | 20 | 30 | 40 | 50 | 51 | 61 | 71 | 72;

but the property itself is this:

...
  features: StructureDtoFeatures;
...

which is not an array.

This part works fine in the Swagger Editor and when creating a client with typescript-angular, the Class is also correct.

...
    features?: Array<number>;
...

Error when generating parameters by reference

When specifying a global parameter in documentation.parameters and referencing to this parameter in the request ('$ref': '#/parameters/someParam') specification an error occurs when generating the client.

(node:93171) UnhandledPromiseRejectionWarning: Error: Request failed with status code 500
    at createError (/path/to/project/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/path/to/project/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/path/to/project/node_modules/axios/lib/adapters/http.js:237:11)
    at IncomingMessage.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1183:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
(node:93171) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:93171) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Insufficient number of arguments or no entry found.
Alternatively, run 'webpack(-cli) --help' for usage info.

Hash: 7532bd6d1996f82068cf
Version: webpack 4.35.0
Time: 31ms
Built at: 10/16/2019 11:54:09 AM

ERROR in Entry module not found: Error: Can't resolve './our-project.js' in '/path/to/project/bin/build'

Generating wrong enums

  4977 |   
  4978 |   export enum WallContentType{
> 4979 |     1|2|3
       |      ^
  4980 |   }

(node:17056) UnhandledPromiseRejectionWarning: SyntaxError: ',' expected. (4979:6)

can't support openapi3.0

when i use a json file with openapi3.0, like:

{
"openapi" : "3.0.0",
"info" : {
"title" : "Swagger Petstore",
"description" : "This is a sample Petstore server. You can find\nout more about Swagger at\nhttp://swagger.io or on\nirc.freenode.net, #swagger.\n",
"termsOfService" : "http://swagger.io/terms/",
"contact" : {
"email" : "[email protected]"
},
...

the following error occured:
error TypeError: Cannot read property 'slice' of undefined
at Object.refClassName (D:*\swagger-axios-codegen\example\node_modules\swagger-axios-codegen\dist\utils.js:24:22)
at params.forEach.p (D:*
\swagger-axios-codegen\dist\requestCodegen\getRequestParameters.js:21:36)
at Array.forEach ()
at Object.getRequestParameters (D:*\example\node_modules\swagger-axios-codegen\dist\requestCodegen\getRequestParameters.js:16:12)
at Object.requestCodegen (D:*
\example\node_modules\swagger-axios-codegen\dist\requestCodegen\index.js:28:59)
at codegen (D:*\example\node_modules\swagger-axios-codegen\dist\index.js:140:45)
at Object. (D:*
\example\swagger\codegen.js:3:1)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)

A couple of suggestions

Hi @Manweill ,

it's me again. Since I found it hard debugging for #13 , I have a couple of improvements that I'd suggest you to add when you have time.

Add Source Maps

I suggest you to add a tsconfig.json file with compilerOptions.sourceMap: true, or alternatively add --sourceMap=true to the build npm script.
Other useful options for optimizing the build and source files are here

Template with a template library

I saw many templates defined as JS/TS template strings in template.ts. However they are hardly readable.
Maybe using a template library such as hanldebarsjs and having separated files for each template can improve readability and debugging of this important part of the code.

Constants are not generated

Hi guys,

Is the any way to tell codegen to generate constants?

My class looks like:

    public class DemoPermissions
    {
        public const string customers_view = "customers_view";
        public const string customers_manage = "customers_manage";
    }

Currently codegen generates the following ts:

export class DemoPermissions {
  constructor(data: undefined | any = {}) {}
}

I use those constants as permissions. The reason I use const instead of enum is to be able to pass them into the attributes and because I will have many permission classes (cannon have many enums against one property):

        [DataRouteAction(Perms = DemoPermissions.customers_view)]
        public async Task<IList<CustomerVm>> GetCustomers()
        {
            ...
        }

In the same time I would like to use those constants in vuejs:

<button v-if="isAllowed(DemoPermissions.customers_view)" />

I assume constants can be generated as static properties or as enums in typescript. The tricky thing is to pass the value instead of the property name. In my situation it wont be a case:

export class DemoPermissions {
  static customers_view = 'customers_view';
  static customers_manage = 'customers_manage';
  static some_property = 'some_value'; // value can be different from property name !!!
}

Promise result is Any instead of the actual Type in open api v3

"swagger-axios-codegen": "0.9.10"
After switching my project to OpenApi v3 the rendered services lose the actual response type and have any instead. Is it intentional or a bug?
/services/index.ts changes after switching to v3:
image

The api v3 (Swashbuckle.AspNetCore 5.0.0):
image

Operation:
image

Component:
image

Add baseUrl option into ISwaggerOptions

I know there is a way to customize base url for all APIs, but it's better to add an option into ISwaggerOption. Cause most time we need to specify the backend server host and port.

What I want is some thing looks like:

swaggerCodegen.codegen({
    useStaticMethod: false,
    baseUrl: "http://localhost:8000/", // here we can set base url for APIs
    remoteUrl: "http://localhost:8000/v2/api-docs",
    outputDir: "./src/service/",
    fileName: "ApiServices.ts"
});

and I look through the source code, there may useless tips(lol):

${options.useStaticMethod ? 'static' : ''} ${camelcase(name)}(${parameters}options:IRequestOptions={}):Promise<${responseType}> {
  return new Promise((resolve, reject) => {
    const configs:IRequestConfig = {...options, method: "${method}" };
    configs.headers = {
      ...options.headers,
      'Content-Type':'${contentType}'
    }
    let url = '${path}'  // add new features here?  let url = '${baseUrl + path}' 
    ${pathReplace}
    configs.url = url
    ${parsedParameters && queryParameters.length > 0
        ? 'configs.params = {' + queryParameters.join(',') + '}'
        : ''}
    let data = ${parsedParameters && bodyParameters.length > 0
        ? '{' + bodyParameters.join(',') + '}'

Support response types

Currently response types are not typed (e.g. return type is always Promise< any >). It would be great to have these typed as well :)

I might look into this myself, when I find time!

ts error: An enum member cannot have a numeric name.

Reproduction

When we got an enum like this in definitions :

 "ResponseEntity": {
      "type": "object",
      "properties": {
        "body": { "type": "object" },
        "statusCode": {
          "type": "string",
          "enum": [
            "100",
            "101",
          ]
        },
        "statusCodeValue": { "type": "integer", "format": "int32" }
      },
      "title": "ResponseEntity"
    },

code generation will generate an enum like this

export enum EnumResponseEntityStatusCode {
  '100' = '100',
  '101' = '101'
}

Triggering a .ts error An enum member cannot have a numeric name.

Will make a PR soon to fix it

Trouble with generating an array of number enums

The generator removes an array from the swagger.json schema when the array contains a number enum.
simplified example:

{ 
  "definitions": {
    "MyModel": {
      "type":"object",
      "properties": {
          "foo": {
          "uniqueItems": true,
          "type": "array",
          "items": {
            "format": "int32",
            "enum": [
              0,
              1,
              2,
              4,
              8
            ],
            "type": "integer"
          }
        },
      }
    }
  }
}

the generated class will look something like this:

export class MyModel {
  foo: 0 | 1 | 2 | 4 | 8;
  constructor(data?: any) {
    if (data) {
      this['foo'] = data['foo'];
    }
  }
}

Sorry for the low quality example :(

I believe, I have found the error, and I will create a PR later.

Can you confirm its still an issue in your latest development branch ?

TypeError: types is not iterable

After upgrading from 0.9.7 to 0.9.9 got the following error:
npm: '6.13.6',
node: '12.14.1',

(node:26524) UnhandledPromiseRejectionWarning: TypeError: types is not iterable
    at Object.setDefinedGenericTypes (C:\Code\swagger-axios-codegen\dist\utils.js:11:79)
    at C:\Code\swagger-axios-codegen\dist\index.js:52:17
    at Generator.next (<anonymous>)
    at C:\Code\swagger-axios-codegen\dist\index.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (C:\Code\swagger-axios-codegen\dist\index.js:4:12)
    at codegen (C:\Code\swagger-axios-codegen\dist\index.js:48:12)
    at Object.<anonymous> (C:\Code\Maximus\src\Maximus.App\codegen.js:3:1)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)

My codegen.js looks like this:

const { codegen } = require("swagger-axios-codegen");

codegen({
	serviceNameSuffix: "Service",
	enumNamePrefix: "Enum",
	methodNameMode: "operationId",
	remoteUrl: "http://localhost:8050/api/v1/swagger.json",
	outputDir: "./src/services",
	strictNullChecks: false,
	useStaticMethod: true,
	useCustomerRequestInstance: false,
	include: [],
	modelMode: "class"
});

useClassTransformer doesn't work when modelMode is set to interface

Problem Statement:
As mentioned in #32 it is desirable to convert date types (date and date-time) to Date object instead of string. This currently only works with modelMode: "class". Setting modelMode: "interface" results in an error.

How to reproduce:
Run swagger-axios-codegen with following configuration:

const { codegen } = require("swagger-axios-codegen");

codegen({
  methodNameMode: "operationId",
  remoteUrl: "https://petstore.swagger.io/v2/swagger.json", 
  useClassTransformer: true,
  outputDir: "./out",
  modelMode: "interface",
  useStaticMethod: true
});

Example Error:

Argument of type 'unknown[]' is not assignable to parameter of type 'Pet | PromiseLike | undefined'.
Property 'then' is missing in type 'unknown[]' but required in type 'PromiseLike'

In addition to that, dates are not transformed to Date:

// https://petstore.swagger.io/v2/swagger.json
...
  "Order": {
    ...
     "shipDate": {
       "type": "string",
       "format": "date-time"
     }
    ...
  }
...
// generated index.ts
export interface Order {
 ...
  shipDate: string; // should be Date
 ...
}

TypeError: The "path" argument must be of type string

After upgrading from 0.9.7 to 0.9.9 got the following error:
npm: '6.13.6',
node: '12.14.1',

(node:2816) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:112:11)
    at Object.resolve (path.js:139:9)
    at definitionHeader (C:\Code\Maximus\src\Maximus.App\node_modules\swagger-axios-codegen\dist\templates\serviceHeader.js:124:53)
    at Object.serviceHeader (C:\Code\Maximus\src\Maximus.App\node_modules\swagger-axios-codegen\dist\templates\serviceHeader.js:44:5)
    at C:\Code\Maximus\src\Maximus.App\node_modules\swagger-axios-codegen\dist\index.js:73:31
    at Generator.next (<anonymous>)
    at fulfilled (C:\Code\Maximus\src\Maximus.App\node_modules\swagger-axios-codegen\dist\index.js:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:94:5)

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined

Using version 0.9.4, I am getting following error (node version 10.17.0)

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined

when trying to generate from following json:

{
  "swagger": "2.0",
  "info": {
    "title": "services/auth.proto",
    "version": "version not set"
  },
  "schemes": [
    "http",
    "https"
  ],
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "paths": {
    "/auth/v1/change_password/{sub}": {
      "put": {
        "operationId": "ChangePassword",
        "responses": {
          "200": {
            "description": "A successful response.",
            "schema": {
              "$ref": "#/definitions/pbChangePasswordResponse"
            }
          }
        },
        "parameters": [
          {
            "name": "sub",
            "in": "path",
            "required": true,
            "type": "string"
          },
          {
            "name": "body",
            "in": "body",
            "required": true,
            "schema": {
              "$ref": "#/definitions/pbChangePasswordRequest"
            }
          }
        ],
        "tags": [
          "Users"
        ]
      }
    },
    "/auth/v1/reset_user": {
      "post": {
        "operationId": "ResetUser",
        "responses": {
          "200": {
            "description": "A successful response.",
            "schema": {
              "$ref": "#/definitions/pbResetUserResponse"
            }
          }
        },
        "parameters": [
          {
            "name": "body",
            "in": "body",
            "required": true,
            "schema": {
              "$ref": "#/definitions/pbResetUserRequest"
            }
          }
        ],
        "tags": [
          "Users"
        ]
      }
    },
    "/auth/v1/user": {
      "post": {
        "operationId": "CreateUser",
        "responses": {
          "200": {
            "description": "A successful response.",
            "schema": {
              "$ref": "#/definitions/pbCreateUserResponse"
            }
          }
        },
        "parameters": [
          {
            "name": "body",
            "in": "body",
            "required": true,
            "schema": {
              "$ref": "#/definitions/pbCreateUserRequest"
            }
          }
        ],
        "tags": [
          "Users"
        ]
      }
    },
    "/auth/v1/user/list": {
      "get": {
        "operationId": "ListUsers",
        "responses": {
          "200": {
            "description": "A successful response.",
            "schema": {
              "$ref": "#/definitions/pbListUsersResponse"
            }
          }
        },
        "parameters": [
          {
            "name": "pagination.enabled",
            "in": "query",
            "required": false,
            "type": "boolean",
            "format": "boolean"
          },
          {
            "name": "pagination.limit",
            "in": "query",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "pagination.page",
            "in": "query",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "pagination.skip",
            "in": "query",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "pagination.total_rows",
            "in": "query",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "pagination.total_pages",
            "in": "query",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "pagination.prev_page",
            "in": "query",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "pagination.next_page",
            "in": "query",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "ordering.field",
            "in": "query",
            "required": false,
            "type": "string"
          },
          {
            "name": "ordering.dir",
            "in": "query",
            "required": false,
            "type": "string"
          }
        ],
        "tags": [
          "Users"
        ]
      }
    },
    "/auth/v1/user/{id}": {
      "get": {
        "operationId": "GetUser",
        "responses": {
          "200": {
            "description": "A successful response.",
            "schema": {
              "$ref": "#/definitions/pbGetUserResponse"
            }
          }
        },
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "type": "string",
            "format": "uint64"
          }
        ],
        "tags": [
          "Users"
        ]
      }
    }
  },
  "definitions": {
    "errorsStatus": {
      "type": "object",
      "properties": {
        "code": {
          "type": "integer",
          "format": "int32",
          "description": "The status code, which should be an enum value of\n[google.rpc.Code][google.rpc.Code]."
        },
        "message": {
          "type": "string",
          "description": "A developer-facing error message, which should be in English. Any\nuser-facing error message should be localized and sent in the\n[google.rpc.Status.details][google.rpc.Status.details] field, or localized\nby the client."
        },
        "details": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/protobufAny"
          },
          "description": "A list of messages that carry the error details.  There is a common set of\nmessage types for APIs to use."
        }
      },
      "description": "- Simple to use and understand for most users\n- Flexible enough to meet unexpected needs\n\n# Overview\n\nThe `Status` message contains three pieces of data: error code, error\nmessage, and error details. The error code should be an enum value of\n[google.rpc.Code][google.rpc.Code], but it may accept additional error codes\nif needed.  The error message should be a developer-facing English message\nthat helps developers *understand* and *resolve* the error. If a localized\nuser-facing error message is needed, put the localized message in the error\ndetails or localize it in the client. The optional error details may contain\narbitrary information about the error. There is a predefined set of error\ndetail types in the package `google.rpc` that can be used for common error\nconditions.\n\n# Language mapping\n\nThe `Status` message is the logical representation of the error model, but it\nis not necessarily the actual wire format. When the `Status` message is\nexposed in different client libraries and different wire protocols, it can be\nmapped differently. For example, it will likely be mapped to some exceptions\nin Java, but more likely mapped to some error codes in C.\n\n# Other uses\n\nThe error model and the `Status` message can be used in a variety of\nenvironments, either with or without APIs, to provide a\nconsistent developer experience across different environments.\n\nExample uses of this error model include:\n\n- Partial errors. If a service needs to return partial errors to the client,\n    it may embed the `Status` in the normal response to indicate the partial\n    errors.\n\n- Workflow errors. A typical workflow has multiple steps. Each step may\n    have a `Status` message for error reporting.\n\n- Batch operations. If a client uses batch request and batch response, the\n    `Status` message should be used directly inside batch response, one for\n    each error sub-response.\n\n- Asynchronous operations. If an API call embeds asynchronous operation\n    results in its response, the status of those operations should be\n    represented directly using the `Status` message.\n\n- Logging. If some API errors are stored in logs, the message `Status` could\n    be used directly after any stripping needed for security/privacy reasons.",
      "title": "The `Status` type defines a logical error model that is suitable for\ndifferent programming environments, including REST APIs and RPC APIs. It is\nused by [gRPC](https://github.com/grpc). The error model is designed to be:"
    },
    "paginationPager": {
      "type": "object",
      "properties": {
        "enabled": {
          "type": "boolean",
          "format": "boolean"
        },
        "limit": {
          "type": "integer",
          "format": "int32"
        },
        "page": {
          "type": "integer",
          "format": "int32"
        },
        "skip": {
          "type": "integer",
          "format": "int32"
        },
        "total_rows": {
          "type": "integer",
          "format": "int32"
        },
        "total_pages": {
          "type": "integer",
          "format": "int32"
        },
        "prev_page": {
          "type": "integer",
          "format": "int32"
        },
        "next_page": {
          "type": "integer",
          "format": "int32"
        }
      }
    },
    "pbChangePasswordRequest": {
      "type": "object",
      "properties": {
        "sub": {
          "type": "string"
        },
        "old_password": {
          "type": "string"
        },
        "password": {
          "type": "string"
        },
        "password_confirmation": {
          "type": "string"
        }
      }
    },
    "pbChangePasswordResponse": {
      "type": "object"
    },
    "pbCreateUserRequest": {
      "type": "object",
      "properties": {
        "username": {
          "type": "string"
        },
        "password": {
          "type": "string"
        },
        "password_confirmation": {
          "type": "string"
        }
      }
    },
    "pbCreateUserResponse": {
      "type": "object",
      "properties": {
        "status": {
          "$ref": "#/definitions/errorsStatus"
        },
        "user": {
          "$ref": "#/definitions/pbUser"
        }
      }
    },
    "pbGetUserResponse": {
      "type": "object",
      "properties": {
        "status": {
          "$ref": "#/definitions/errorsStatus"
        },
        "user": {
          "$ref": "#/definitions/pbUser"
        }
      }
    },
    "pbListUsersResponse": {
      "type": "object",
      "properties": {
        "status": {
          "$ref": "#/definitions/errorsStatus"
        },
        "pagination": {
          "$ref": "#/definitions/paginationPager"
        },
        "users": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/pbUser"
          }
        }
      }
    },
    "pbOrdering": {
      "type": "object",
      "properties": {
        "field": {
          "type": "string"
        },
        "dir": {
          "type": "string"
        }
      }
    },
    "pbResetUserRequest": {
      "type": "object",
      "properties": {
        "email": {
          "type": "string"
        }
      }
    },
    "pbResetUserResponse": {
      "type": "object",
      "properties": {
        "status": {
          "$ref": "#/definitions/errorsStatus"
        },
        "mail_response": {
          "type": "string"
        }
      }
    },
    "pbUser": {
      "type": "object",
      "properties": {
        "id": {
          "type": "string",
          "format": "uint64"
        },
        "username": {
          "type": "string"
        }
      }
    },
    "pbUserFilter": {
      "type": "object"
    },
    "protobufAny": {
      "type": "object",
      "properties": {
        "type_url": {
          "type": "string",
          "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n  value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n  URL, or have them precompiled into a binary to avoid any\n  lookup. Therefore, binary compatibility needs to be preserved\n  on changes to types. (Use versioned type names to manage\n  breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics."
        },
        "value": {
          "type": "string",
          "format": "byte",
          "description": "Must be a valid serialized protocol buffer of the above specified type."
        }
      },
      "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n    Foo foo = ...;\n    Any any;\n    any.PackFrom(foo);\n    ...\n    if (any.UnpackTo(\u0026foo)) {\n      ...\n    }\n\nExample 2: Pack and unpack a message in Java.\n\n    Foo foo = ...;\n    Any any = Any.pack(foo);\n    ...\n    if (any.is(Foo.class)) {\n      foo = any.unpack(Foo.class);\n    }\n\n Example 3: Pack and unpack a message in Python.\n\n    foo = Foo(...)\n    any = Any()\n    any.Pack(foo)\n    ...\n    if any.Is(Foo.DESCRIPTOR):\n      any.Unpack(foo)\n      ...\n\n Example 4: Pack and unpack a message in Go\n\n     foo := \u0026pb.Foo{...}\n     any, err := ptypes.MarshalAny(foo)\n     ...\n     foo := \u0026pb.Foo{}\n     if err := ptypes.UnmarshalAny(any, foo); err != nil {\n       ...\n     }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n    package google.profile;\n    message Person {\n      string first_name = 1;\n      string last_name = 2;\n    }\n\n    {\n      \"@type\": \"type.googleapis.com/google.profile.Person\",\n      \"firstName\": \u003cstring\u003e,\n      \"lastName\": \u003cstring\u003e\n    }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n    {\n      \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n      \"value\": \"1.212s\"\n    }"
    }
  }
}

With JIRA API it shows an error

Trying to generate a client from the JIRA API at:
https://developer.atlassian.com/cloud/jira/platform/swagger.v3.json

shows the error:

openApi version: 3.0.1
isV3 true
(node:25456) UnhandledPromiseRejectionWarning: Error: Could not find property type on schema
    at Object.getRequestBody (C:\Users\kulcsar\source\repos\demo\node_modules\swagger-axios-codegen\dist\requestCodegen\getRequestBody.js:29:19)
    at Object.requestCodegen (C:\Users\kulcsar\source\repos\demo\node_modules\swagger-axios-codegen\dist\requestCodegen\index.js:46:54)
    at C:\source\repos\demo\node_modules\swagger-axios-codegen\dist\index.js:74:62

Any ideas what could cause this?
Any help is much appreciated, this is a great codegen and I'm using it successfully on other APIs but been stuck on the JIRA API.

Many thanks!

Transform Date strings

Swagger does not have an own Date type. Instead Date is supported via string (https://swagger.io/docs/specification/data-models/data-types/). The documentation might be for OpenAPI 3.0, but the part about the Date is also valid for 2.0. The format attribute supports two Date formats:

  • date – full-date notation as defined by RFC 3339, section 5.6, for example, 2017-07-21
  • date-time – the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z

It would be a huge plus, if these types where transformed correctly whitin a DTO. So when receiving a response the DTO could just transform the string of these fields to date and vice versa when sending a request.

One idea might be to use https://github.com/typestack/class-transformer within the DTOs and transform them with the plainToClass method.

I know it is a lot to ask, but it would be a great feature which would save a lot of work because i work with a lot of dates.

This codegen is already great and this is the only thing i am missing so far .Thanks!

v.enum.map is not a function

Error appears in swagger-axios-codegen/dist/definitionCodegen/propTrueType.js:50:34

If enum is swagger output is defined as object instead of array codegen shows this message.

Solution is:

      if(typeof v.enum === "object") {
           v.enum = Object.values(v.enum);
       }

Error: please inject yourself instance like axios

Good afternoon.
Thanks so much for a great plugin.

Help to deal with the question.
I use the generated code in VUE. When I try to access the method, I get an error in the promise ("Error: please inject yourself instance like axios").

Thanks for the help

Proposal: Add functionality to pass default axios instance to generated services

Hi, thank you for the great library.

I'm trying to use this library with Nuxt.js and @nuxtjs/auth.
The module set the authentication header to nuxt's $axios intance automatically when auth succeed.

I would like to set this instance into the service classes that are generated by the codegen.
How about adding the functionality like this?

The code following is example:

// Generated `service/index.ts`
import axiosStatic, { AxiosPromise, AxiosRequestConfig, AxiosInstance } from 'axios';
export interface IRequestOptions {
  headers?: any;
}

// Add options interface
export interface ServiceOptions {
  axios?: AxiosInstance,
}

// Add default options
export const serviceOptions: ServiceOptions = {
};

// Instance selector
function axios(configs: AxiosRequestConfig): AxiosPromise {
  return serviceOptions.axios? serviceOptions.axios.request(configs) : axiosStatic(configs);
}

// no changes in other generated codes.
// user side:

// injector (this example is the @nuxtjs/auth's plugins)
import {serviceOptions} from "../service";
export default ({ app }) => {
  serviceOptions.axios = app.$axios;
}

// api call 
const res = await SomeService.fooGet(params); // this api is assumed that requires authentication

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.