{"id":22770993,"url":"https://github.com/manweill/swagger-axios-codegen","last_synced_at":"2025-05-14T18:07:07.049Z","repository":{"id":31867868,"uuid":"129564988","full_name":"Manweill/swagger-axios-codegen","owner":"Manweill","description":"swagger client to use axios and typescript","archived":false,"fork":false,"pushed_at":"2025-04-03T05:47:59.000Z","size":984,"stargazers_count":310,"open_issues_count":6,"forks_count":87,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-05-14T18:07:00.505Z","etag":null,"topics":["axios","codegen","fly","javascript","openapi","swagger","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Manweill.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-04-15T00:37:24.000Z","updated_at":"2025-05-12T13:03:18.000Z","dependencies_parsed_at":"2024-01-12T05:39:57.370Z","dependency_job_id":"9623bf9e-cf58-464d-8f76-67c36fe8a28a","html_url":"https://github.com/Manweill/swagger-axios-codegen","commit_stats":{"total_commits":370,"total_committers":37,"mean_commits":10.0,"dds":0.3810810810810811,"last_synced_commit":"9b2f8f3d74aebede46957223653921c4a067093a"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Manweill%2Fswagger-axios-codegen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Manweill%2Fswagger-axios-codegen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Manweill%2Fswagger-axios-codegen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Manweill%2Fswagger-axios-codegen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Manweill","download_url":"https://codeload.github.com/Manweill/swagger-axios-codegen/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254198515,"owners_count":22030966,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["axios","codegen","fly","javascript","openapi","swagger","typescript"],"created_at":"2024-12-11T16:11:36.117Z","updated_at":"2025-05-14T18:07:02.038Z","avatar_url":"https://github.com/Manweill.png","language":"TypeScript","readme":"# swagger-axios-codegen\nA swagger client uses axios and typescript\n\n\n￼[![NpmVersion](https://img.shields.io/npm/v/swagger-axios-codegen.svg)](https://www.npmjs.com/package/swagger-axios-codegen)\n￼[![npm](https://img.shields.io/npm/dm/swagger-axios-codegen.svg)](https://www.npmjs.com/package/swagger-axios-codegen)\n[![open issues](https://img.shields.io/github/issues-raw/manweill/swagger-axios-codegen.svg)](https://img.shields.io/github/issues-raw/manweill/swagger-axios-codegen.svg)\n\n```\n\u003c v0.16 require node \u003e v10.0.0\n\n\u003e= v0.16 require node \u003e= v16\n```\n\nit will always resolve `axios.response.data` or reject `axios.error` with Promise\n\nsupport other similar to `axios` library, for example [Fly.js](https://github.com/wendux/fly), required setting `ISwaggerOptions.useCustomerRequestInstance = true`\n\nthe es6 version is generated by calling typescript\n\nWelcome PRs and commit issue\n\nBy the way. you can support this repo via Star star sta st s... ⭐️ ⭐️ ⭐️ ⭐️ ⭐️\n\n\n## [Example](./example)\n\n## [ChangeLog](./CHANGELOG.md)\n\n## [Contributing](./CONTRIBUTING.md)\n\n## Get Started\n\n```\n  yarn add swagger-axios-codegen\n```\n\n```js\n\nexport interface ISwaggerOptions {\n  serviceNameSuffix?: string\n  enumNamePrefix?: string\n  methodNameMode?: 'operationId' | 'path' | 'shortOperationId' | ((reqProps: IRequestMethod) =\u003e string)\n  classNameMode?: 'parentPath' | 'normal' | ((path: string, method: string, reqProps:IRequestMethod) =\u003e string)\n  /** only effect classNameMode='parentPath' */\n  pathClassNameDefaultName?: string\n  outputDir?: string\n  fileName?: string\n  remoteUrl?: string\n  source?: any\n  useStaticMethod?: boolean | undefined\n  useCustomerRequestInstance?: boolean | undefined\n  include?: Array\u003cstring | IInclude\u003e\n  /** include types which are not included during the filtering **/\n  includeTypes?: Array\u003cstring\u003e\n  format?: (s: string) =\u003e string\n  /** match with tsconfig */\n  strictNullChecks?: boolean | undefined\n  /** definition Class mode */\n  modelMode?: 'class' | 'interface'\n  /** use class-transformer to transform the results */\n  useClassTransformer?: boolean\n  /** force the specified swagger or openAPI version, */\n  openApi?: string | undefined\n  /** extend file url. It will be inserted in front of the service method */\n  extendDefinitionFile?: string | undefined\n  /** mark generic type */\n  extendGenericType?: string[] | undefined\n  /** generate validation model (class model mode only) */\n  generateValidationModel?: boolean\n  /** split request service.  Can't use with sharedServiceOptions*/\n  multipleFileMode?: boolean | undefined\n  /** url prefix filter*/\n  urlFilters?: string[] | null | undefined\n  /** shared service options to multiple service. Can't use with MultipleFileMode */\n  sharedServiceOptions?: boolean | undefined\n  /** use parameters in header or not*/\n  useHeaderParameters?: boolean\n}\n\nconst defaultOptions: ISwaggerOptions = {\n  serviceNameSuffix: 'Service',\n  enumNamePrefix: 'Enum',\n  methodNameMode: 'operationId',\n  classNameMode: 'normal',\n  PathClassNameDefaultName: 'Global',\n  outputDir: './service',\n  fileName: 'index.ts',\n  useStaticMethod: true,\n  useCustomerRequestInstance: false,\n  include: [],\n  strictNullChecks: true,\n  /** definition Class mode ,auto use interface mode to streamlined code*/\n  modelMode?: 'interface',\n  useClassTransformer: false\n}\n\n```\n\n### use local swagger api json\n\n```js \n\nconst { codegen } = require('swagger-axios-codegen')\ncodegen({\n  methodNameMode: 'operationId',\n  source: require('./swagger.json')\n})\n\n\n```\n\n### use remote swagger api json\n```js \n\nconst { codegen } = require('swagger-axios-codegen')\ncodegen({\n  methodNameMode: 'operationId',\n  remoteUrl:'You remote Url'\n})\n\n\n```\n\n### use static method\n\n```js\ncodegen({\n    methodNameMode: 'operationId',\n    remoteUrl: 'http://localhost:22742/swagger/v1/swagger.json',\n    outputDir: '.',\n    useStaticMethod: true\n});\n\n```\n\nbefore\n\n\n```js\n\nimport { UserService } from './service'\nconst userService = new UserService()\nawait userService.GetAll();\n\n```\n\nafter\n\n```js\n\nimport { UserService } from './service'\n\nawait UserService.GetAll();\n\n```\n\n\n### use custom axios.instance\n\n```js\nimport axios from 'axios'\nimport { serviceOptions } from './service'\nconst instance = axios.create({\n  baseURL: 'https://some-domain.com/api/',\n  timeout: 1000,\n  headers: {'X-Custom-Header': 'foobar'}\n});\n\nserviceOptions.axios = instance\n\n```\n\n### use other library\n\n```js\nimport YourLib from '\u003cYour lib\u003e'\nimport { serviceOptions } from './service'\n\nserviceOptions.axios = YourLib\n\n```\n\n### filter service and method \n\nfliter by [multimatch](https://github.com/sindresorhus/multimatch) using 'include' setting\n\n```js\ncodegen({\n  methodNameMode: 'path',\n  source: require('../swagger.json'),\n  outputDir: './swagger/services',\n  include: [\n    '*',\n    // 'Products*',\n    '!Products',\n    { 'User': ['*', '!history'] },\n  ]\n})\n```\n\nIf you are using special characters in your service name (which is the first tag) you must assume they have been escaped.\n\nFor example the service names are `MyApp.FirstModule.Products`, `MyApp.FirstModule.Customers`, `MyApp.SecondModule.Orders`:\n\n```json\n// API\n\"paths\": {\n  \"/Products/Get\": {\n    \"post\": {\n      \"tags\": [\n        \"MyApp.FirstModule.Products\"\n      ],\n      \"operationId\": \"Get\",\n```\n\n```js\n// Codegen config\ncodegen({\n  methodNameMode: 'path',\n  source: require('../swagger.json'),\n  outputDir: './swagger/services',\n  include: ['MyAppFirstModule*'] // Only Products and Customers will be included. As you can see dots are escaped being contract names.\n})\n```\n\n\n### use class transformer to transform results\n\nThis is helpful if you want to transform dates to real date \nobjects. Swagger can define string formats for different types. Two if these formats are `date` and `date-time`\n\nIf a `class-transformer` is enabled and a format is set on a string, the result string will be transformed to a `Date` instance\n\n\n// swagger.json\n```json\n{\n  \"ObjectWithDate\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"date\": {\n        \"type\": \"string\",\n        \"format\": \"date-time\"\n      }\n    }\n  }\n}\n```\n\n```js\n\nconst { codegen } = require('swagger-axios-codegen')\ncodegen({\n  methodNameMode: 'operationId',\n  source:require('./swagger.json'),\n  useClassTransformer: true,\n})\n```\n\nResulting class:\n```ts\nexport class ObjectWithDate {\n  @Expose()\n  @Type(() =\u003e Date)\n  public date: Date;\n}\n```\n\nThe service method will transform the json response and return an instance of this class\n\n### use validation model\n\n```js\ncodegen({\n    ...\n    modelMode: 'class',\n    generateValidationModel: true\n});\n```\n\nThe option above among with class model mode allows to render the model validation rules. The result of this will be as follows:\n\n```js\nexport class FooFormVm {\n  'name'?: string;\n  'description'?: string;\n \n  constructor(data: undefined | any = {}) {\n    this['name'] = data['name'];\n    this['description'] = data['description'];\n  }\n \n  public static validationModel = {\n    name: { required: true, maxLength: 50 },\n    description: { maxLength: 250 },\n  };\n}\n```\nSo you can use the validation model in your application:\n\n```js\nfunction isRequired(vm: any, fieldName: string): boolean {\n  return (vm \u0026\u0026 vm[fieldName] \u0026\u0026 vm[fieldName].required === true);\n}\nfunction maxLength(vm: any, fieldName: string): number {\n  return (vm \u0026\u0026 vm[fieldName] \u0026\u0026 vm[fieldName].maxLength ? vm[fieldName].maxLength : 4000);\n}\n```\nNow you can use the functions\n```js\nvar required = isRequired(FooFormVm.validationModel, 'name');\nvar maxLength = maxLength(FooFormVm.validationModel, 'description');\n```\nAt the moment there are only two rules are supported - `required` and `maxLength`.\n\n## Some Solution\n\n### 1.Reference parameters\n\nsee in [#53](https://github.com/Manweill/swagger-axios-codegen/issues/53), use package [json-schema-ref-parser](https://github.com/APIDevTools/json-schema-ref-parser)\n\n\n### 2.With `Microservice Gateway`\n\n```js\nconst {codegen} = require('swagger-axios-codegen')\nconst axios = require('axios')\n// host 地址\nconst host = 'http://your-host-name'\n\n// \nconst modules = [\n  ...\n]\n\naxios.get(`${host}/swagger-resources`).then(async ({data}) =\u003e {\n  console.warn('code', host)\n  for (let n of data) {\n    if (modules.includes(n.name)) {\n      try {\n        await codegen({\n          remoteUrl: `${host}${n.url}`,\n          methodNameMode: 'operationId',\n          modelMode: 'interface',\n          strictNullChecks: false,\n          outputDir: './services',\n          fileName: `${n.name}.ts`,\n          sharedServiceOptions: true,\n          extendDefinitionFile: './customerDefinition.ts',\n        })\n      } catch (e) {\n        console.log(`${n.name} service error`, e.message)\n      }\n    }\n  }\n})\n\n```\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanweill%2Fswagger-axios-codegen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmanweill%2Fswagger-axios-codegen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanweill%2Fswagger-axios-codegen/lists"}