axios-api,js結構化定義、調用業務api接口。

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可能需要重啓才能顯示請求示例的調用提示!

目錄

安裝使用

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:

一層:

image
image

二層:

image
image

調用提示:

image

定義了metadata:

調用提示:

image
image

關於上述示例

示例使用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'

保留當前正在進行的請求,中止後面重複的請求。

image

cancel: 'previous'

放棄之前的請求,保留最新提交的請求。

image

緩存cache

cache: 3000

3秒內不再request請求,從緩存中獲取歷史返回結果。

image

接口定義配置說明

配置 類型 必填 默認值 說明
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"
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章