# yz-gen-api 根据 swagger 文档，生成 api 代码

## 根据 swagger API v2 生成接口代码

## 安装

```bash
yarn add @yzfe/gen-api -D
yarn add axios 
```

## 使用

```bash
npx yz-gen-api build https://petstore.swagger.io/v2/swagger.json -o src/api
```

## 命令

```bash
npx yz-gen-api build -h
```

```
yz-gen-api build <swaggerUrl>

根据 swagger 文档，生成 api 代码

选项：
  --version, -v  显示版本号                                               [布尔]
  --help, -h                                                              [布尔]
  --outPath, -o  生成目录                                                 [必需]
```

## Vue 最佳实现

修改 api 入口文件 `index.ts`

```ts
import * as http from './http'
import client from './client'
import Vue from 'vue'

const api = {
    http,
    defs: client.defs,
    modules: client.modules
}


declare module 'vue/types/vue' {
    interface Vue {
        $api: typeof api
    }
}

export function install(vue: typeof Vue) {
    Object.defineProperty(vue.prototype, '$api', {
        get() {
            return api
        }
    })
}

export default api

```

### Api request / response 值初始化

```ts
export default class Login extends Vue {
    protected loginReq: defs.AuthenticationAuthbasicReq = new this.$api.defs.AuthenticationAuthbasicReq()
}

```
