1.0.0 • Published 3 years ago

yapi-autoapi v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

yapi-autoapi

YAPI 接口自动化,生成 ts 文件,即用即取

install

npm i yapi-autoapi -g

初始化

autoapi init

创建 autoapi.config.js 配置文件

// ati.config.js
module.exports = {
  // yapi 项目 url
  url: '',
  // 项目 id
  projectId: '',
  // yapi 项目 token
  token: '',
  // interface 输出目录
  output: '',
  // 项目内的分组 id
  groupId: [],
  // (可选) 自定义 interface name
  customInterfaceName: (name, type) => {
    if (type === 'request') {
      return `${name}RequestType`
    } else {
      return `${name}ResponseType`
    }
  },
  // 支持自定义模板,只需要将按照以下格式传递即可
  // paramsContent, 入参+ 出参的内容,自动生成无需修改
  // functionName, 函数名,自动生成无需修改
  // reqName, 入参名,自动生成无需修改
  // resName, 出参名,自动生成无需修改
  // requestPath, 请求路径,自动生成无需修改
  customTemplate: (
    functionName,
    requestPath,
    requestInterfaceName,
    responseInterfaceName,
    paramsContent
  ) => {
    return `
    import request from 'request'

    ${paramsContent}
    
    export async function ${functionName}(data?: ${requestInterfaceName}): Promise<${responseInterfaceName}> {
      return request(${requestPath}, {
        method: 'post',
        data
      })
    }
    `
  }
}

run: 自动生成 request 文件

autoapi run

configs

属性说明类型默认值
urlyapi 项目 urlstring
projectId项目 idstring
tokenyapi 项目 tokenstring
outputinterface 输出目录string
groupId项目内的分组 idstring[]
customInterfaceName自定义 interface nameCustomInterfaceName
customTemplate自定义生成文件内容CustomTemplate

其中CustomTemplate的类型定义如下:

type CustomTemplate = (
  //  生成函数名
  functionName: string,
  //  请求接口地址
  requestPath: string,
  //  请求参数类型名
  requestInterfaceName: string,
  //  响应参数类型名
  responseInterfaceName: string,
  //  参数类型定义内容
  paramsContent: string
) => string

生成结果

import request from './lib/'
/* tslint:disable */
/* This file was automatically generated by auto-request-tool.
 * DO NOT MODIFY IT BY HAND.
 */
export interface UserInfoReq {
  /**
   * 用户id
   */
  userId: string
  /**
   * 用户姓名
   */
  userName?: string
  /**
   * 手机号
   */
  mobile?: string
  /**
   * 是否男性
   */
  male?: boolean
}

export interface UserInfoRes {
  /**
   * id
   */
  id: number
  /**
   * 用户id
   */
  userId: string
  /**
   * 用户姓名
   */
  userName?: string
  /**
   * 手机号
   */
  mobile?: string
  /**
   * 是否男性
   */
  male?: boolean
  /**
   * 头像
   */
  avatar?: string
}

export async function confirmAudit(data: UserInfoReq): Promise<UserInfoRes> {
  return request('/autoapi/request/getUserInfo', {
    method: 'post',
    data
  })
}