关于javascript:axiosapijs结构化定义调用业务api接口

8次阅读

共计 3305 个字符,预计需要花费 9 分钟才能阅读完成。

axios-api

@no-996/axios-api 基于 axios 可建设结构化实例的工具,有以下特点:

  1. 基于 axios,兼容 axios 的 api,可无缝的迁徙应用。
  2. 内置了两种罕用的申请终止(基于 cancelToken)场景,可避免接口反复调用。
  3. 内置了接口调用的缓存机制,在设置的有效期内,可从缓存中取得历史申请后果。
  4. 内置了接口地址模板插入性能,满足基于 url 蕴含变量值的场景。
  5. 要害:通过结构化的 api 定义生成结构化的 api 申请实例,在我的项目中畅快的疾速调用业务接口。配套应用 webpack 插件(@no-996/axios-api-webpack-plugin),能够主动生成 d.ts 申明文件,在 IDE 中能够取得 api 定义的揭示信息。

第一次生成 d.ts 文件后,vscode 可能须要重启能力显示申请示例的调用提醒!

目录

  • 装置应用
  • 结构化的 api 定义
  • 结构化的 api 申请实例
  • 申请停止 cancel
  • 缓存 cache
  • 接口定义配置阐明
  • axios-api 配置阐明
  • 依赖阐明

装置应用

npm install --save @no-996/axios-api
// src/api/index.js
import ApiModule from '@no-996/axios-api'
import options from './options'

export default new ApiModule(
  // 接口定义
  options,
  // axios 配置
  {
    baseURL: 'https://jsonplaceholder.typicode.com',
    onUploadProgress: (progressEvent, percentCompleted) => {console.log(percentCompleted)
    },
  },
  // axios-api 配置
  {
    cacheStorage: localStorage,
    debug: true,
  }
)
import instance from './api'
// 即可依据结构化的实例进行调用,如:// instance.module001.request()
// instance.module001.sub.request()
// instance.module002.request()
// ...

结构化的 api 定义

// src/api/options/index.js
export default [
  {
    name: 'posts',
    des: '帖子',
    url: '/posts',
    params: {userId: undefined,},
    children: [
      {
        name: 'comments',
        des: '评论',
        url: '/posts/{postId}/comments',
        urlParams: {postId: undefined,},
        metadata: {
          urlParams: {
            postId: {
              name: '帖子 id',
              required: true,
            },
          },
        },
      },
    ],
    metadata: {
      params: {
        userId: {
          name: '用户 id',
          des: '用户惟一标识',
          type: 'string',
        },
      },
    },
  },
  {
    name: 'albums',
    url: '/albums',
    des: '专辑',
    params: {id: undefined,},
    children: [],},
  {
    name: 'photos',
    url: '/photos',
    des: '相片',
    params: {},
    children: [],
    cache: 3000,
  },
  {
    name: 'todos',
    url: '/todos',
    des: '待办事项',
    params: {},
    children: [],
    cancel:'current'
  },
  {
    name: 'users',
    url: '/users',
    des: '用户',
    params: {},
    children: [],
    cancel:'previous'
  },
]

结构化的 api 申请实例

通过结构化的 api 定义生成结构化的 api 申请实例,在我的项目中畅快的疾速调用业务接口。

生成 d.ts 申明文件

配套应用 webpack 插件(@no-996/axios-api-webpack-plugin),依据结构化定义,能够主动生成 d.ts 申明文件,在 IDE 中能够取得 api 定义的揭示信息:

没有定义 metadata:

一层:


二层:


调用提醒:

定义了 metadata:

调用提醒:


对于上述示例

示例应用 Vue,并把申请实例挂载至 Vue.prototype 上:

// src/App.vue
import Vue from 'vue'
import instance from './api'
// ...
Vue.prototype.$api = instance
// ...

留神,示例中如此挂载到 Vue.prototype,须要补充针对 Vue.prototype 申明,如下:

// src/index.d.ts
import Vue from 'vue'
import api from '@/api/index'
declare module 'vue/types/vue' {
  interface Vue {$api: typeof api}
}

申请停止 cancel

cancel: ‘current’

保留以后正在进行的申请,停止前面反复的申请。

cancel: ‘previous’

放弃之前的申请,保留最新提交的申请。

缓存 cache

cache: 3000

3 秒内不再 request 申请,从缓存中获取历史返回后果。

接口定义配置阐明

配置 类型 必填 默认值 阐明
baseURL string/function/Promise 原 baseURL 的扩大,反对 function/Promise 返回
onUploadProgress (progressEvent: any, percentCompleted: number) => void / 原 onUploadProgress 的扩大,减少第二参数,返回百分比值
name string / 接口名
des string / 接口形容
cancel ‘current’/’previous’ / 申请停止形式
cache number / 接口后果缓存时长毫秒数
urlOnly boolean / 是否仅返回解决好的 url 地址(交融 params、urlParams)
urlParams object / url 地址模板替换映射
metadata ApiMetadata / 申请参数的元数据形容,用于 d.ts 生成并产生智能提醒
children array<api 配置 > [] api 配置嵌套
/**
 * 参数元数据内容 / Params metadata info
 */
interface ApiMetadataItem {
  /**
   * 参数名
   * / field name
   */
  name: string
  /**
   * 参数形容
   * / field des
   */
  des: string
  // TODO: 参数校验
  /**
   * 参数类型
   * / field type
   */
  type?: string
  /**
   * 参数必填
   * / field required
   */
  required?: boolean
  /**
   * 自定义校验
   * / field validator
   */
  // validator?:
}

/**
 * 参数元数据 / Params metadata
 */
interface ApiMetadata {[index: string]: ApiMetadataItem | string
}

axios-api 配置阐明

配置 类型 默认值 阐明
debug boolean false 是否显示调试日志
cacheStorage CacheStorage / 缓存工具(如:localStorage、sessionStorage)
interface CacheStorage {
  // 获取缓存
  getItem(key: string): string | null
  // 设置缓存
  setItem(key: string, value: string): void
}

依赖阐明

"dependencies": {
  "@types/md5": "2.3.1",
  "@types/qs": "6.9.7",
  "@types/uuid": "8.3.4",
  "axios": "0.24.0",
  "md5": "2.3.0",
  "qs": "6.7.0",
  "uuid": "8.3.2"
}
正文完
 0