0.16.14 • Published 6 days ago

swagger-axios-codegen v0.16.14

Weekly downloads
2,018
License
MIT
Repository
github
Last release
6 days ago

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... ⭐️ ⭐️ ⭐️ ⭐️ ⭐️

Example

ChangeLog

Contributing

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)
      }
    }
  }
})
0.16.14

6 days ago

0.16.12

2 months ago

0.16.13

2 months ago

0.16.11

2 months ago

0.16.10

2 months ago

0.16.9

2 months ago

0.16.8

3 months ago

0.16.7

4 months ago

0.16.6

4 months ago

0.16.5

4 months ago

0.16.4

4 months ago

0.16.3

5 months ago

0.16.0

5 months ago

0.16.2

5 months ago

0.15.12

8 months ago

0.15.10

1 year ago

0.15.11

1 year ago

0.15.9

1 year ago

0.14.3

2 years ago

0.15.4

1 year ago

0.15.5

1 year ago

0.15.6

1 year ago

0.15.7

1 year ago

0.15.8

1 year ago

0.15.0

2 years ago

0.15.1

1 year ago

0.15.2

1 year ago

0.15.3

1 year ago

0.14.0

2 years ago

0.14.1

2 years ago

0.14.2

2 years ago

0.13.0

2 years ago

0.13.1

2 years ago

0.13.2

2 years ago

0.13.3

2 years ago

0.12.10

2 years ago

0.12.9

2 years ago

0.12.8

3 years ago

0.12.7

3 years ago

0.12.6

3 years ago

0.12.5

3 years ago

0.12.4

3 years ago

0.12.3

3 years ago

0.12.2

3 years ago

0.12.1

3 years ago

0.12.0

3 years ago

0.11.16

3 years ago

0.11.15

3 years ago

0.11.14

3 years ago

0.11.12

3 years ago

0.11.13

3 years ago

0.11.11

3 years ago

0.11.10

4 years ago

0.11.9

4 years ago

0.11.8

4 years ago

0.11.7

4 years ago

0.11.6

4 years ago

0.11.5

4 years ago

0.11.4

4 years ago

0.11.3

4 years ago

0.11.2

4 years ago

0.11.1

4 years ago

0.11.0

4 years ago

0.10.6

4 years ago

0.10.5

4 years ago

0.10.4

4 years ago

0.10.3

4 years ago

0.10.1

4 years ago

0.10.2

4 years ago

0.10.0

4 years ago

0.9.17

4 years ago

0.9.16

4 years ago

0.9.15

4 years ago

0.9.14

4 years ago

0.9.13

4 years ago

0.9.12

4 years ago

0.9.11

4 years ago

0.9.10

4 years ago

0.9.9

4 years ago

0.9.8

4 years ago

0.9.7

4 years ago

0.9.6

4 years ago

0.9.5

4 years ago

0.9.4

4 years ago

0.9.3

4 years ago

0.9.2

4 years ago

0.9.0

4 years ago

0.8.3

5 years ago

0.8.2

5 years ago

0.8.1

5 years ago

0.8.0

5 years ago

0.7.4

5 years ago

0.7.3

5 years ago

0.7.2

5 years ago

0.7.1

5 years ago

0.7.0

5 years ago

0.6.2

5 years ago

0.6.1

5 years ago

0.6.0

5 years ago

0.5.10

5 years ago

0.5.9

5 years ago

0.5.8

5 years ago

0.5.7

5 years ago

0.5.6

5 years ago

0.5.5

5 years ago

0.5.4

5 years ago

0.5.3

5 years ago

0.5.2

5 years ago

0.5.1

5 years ago

0.5.0

5 years ago

0.4.2

5 years ago

0.4.1

5 years ago

0.4.0

5 years ago

0.3.4

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.14

6 years ago

0.2.13

6 years ago

0.2.12

6 years ago

0.2.11

6 years ago

0.2.10

6 years ago

0.2.9

6 years ago

0.2.8

6 years ago

0.2.7

6 years ago

0.2.6

6 years ago

0.2.5

6 years ago

0.2.4

6 years ago

0.2.3

6 years ago

0.2.2

6 years ago

0.2.1

6 years ago

0.2.0

6 years ago

0.1.9

6 years ago

0.1.8

6 years ago

0.1.7

6 years ago

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago