Axios api, js structurally defines and invokes business api interfaces.

Posted by eddiegster on Sun, 16 Jan 2022 22:37:31 +0100

axios-api

@no-996/axios-api A tool based on axios that can create structured instances has the following characteristics:

  1. Based on axios and compatible with axios api, it can be migrated and used seamlessly.
  2. Two common request termination scenarios (based on cancelToken) are built in to prevent repeated interface calls.
  3. The built-in caching mechanism for interface calls can obtain historical request results from the cache within the set validity period.
  4. The built-in interface address template insertion function meets the scenarios based on url containing variable values.
  5. Key: generate structured api request instances through structured api definitions, and quickly call business interfaces in the project. Use webpack plug-in( @no-996/axios-api-webpack-plugin ), the d.ts declaration file can be automatically generated, and the api defined reminder information can be obtained in the IDE.

After generating the d.ts file for the first time, vscode may need to restart to display the call prompt of the request example!

catalogue

Installation and use

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(
  // Interface definition
  options,
  // axios configuration
  {
    baseURL: 'https://jsonplaceholder.typicode.com',
    onUploadProgress: (progressEvent, percentCompleted) => {
      console.log(percentCompleted)
    },
  },
  // Axios API configuration
  {
    cacheStorage: localStorage,
    debug: true,
  }
)
import instance from './api'
// It can be called according to the structured instance, such as:
// instance.module001.request()
// instance.module001.sub.request()
// instance.module002.request()
// ...

Structured api definition

// src/api/options/index.js
export default [
  {
    name: 'posts',
    des: 'Posts',
    url: '/posts',
    params: {
      userId: undefined,
    },
    children: [
      {
        name: 'comments',
        des: 'comment',
        url: '/posts/{postId}/comments',
        urlParams: {
          postId: undefined,
        },
        metadata: {
          urlParams: {
            postId: {
              name: 'Posts id',
              required: true,
            },
          },
        },
      },
    ],
    metadata: {
      params: {
        userId: {
          name: 'user id',
          des: 'User unique ID',
          type: 'string',
        },
      },
    },
  },
  {
    name: 'albums',
    url: '/albums',
    des: 'Album',
    params: {
      id: undefined,
    },
    children: [],
  },
  {
    name: 'photos',
    url: '/photos',
    des: 'photo',
    params: {},
    children: [],
    cache: 3000,
  },
  {
    name: 'todos',
    url: '/todos',
    des: 'To do list',
    params: {},
    children: [],
    cancel:'current'
  },
  {
    name: 'users',
    url: '/users',
    des: 'user',
    params: {},
    children: [],
    cancel:'previous'
  },
]

Structured api request instance

The structured api request instance is generated through the structured api definition, and the business interface can be called quickly and smoothly in the project.

Generate d.ts declaration file

Use webpack plug-in( @no-996/axios-api-webpack-plugin ), according to the structured definition, the d.ts declaration file can be automatically generated, and the reminder information of api definition can be obtained in the IDE:

No metadata defined:

First floor:


Second floor:


Call prompt:

metadata defined:

Call prompt:


About the above example

The sample uses Vue and mounts the request instance to Vue On prototype:

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

Note that in the example, Vue. Com is mounted in this way Prototype, which needs to be supplemented for Vue Prototype declaration, as follows:

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

Request abort cancel

cancel: 'current'

Keep the current request in progress and abort the subsequent repeated requests.

cancel: 'previous'

Discard previous requests and keep the latest submitted requests.

Cache cache

cache: 3000

No request will be made within 3 seconds, and the historical return results will be obtained from the cache.

Interface definition configuration description

to configure type Required Default value explain
baseURL string/function/Promise no '' The extension of the original baseURL supports function/Promise return
onUploadProgress (progressEvent: any, percentCompleted: number) => void no / The extension of the original onUploadProgress adds the second parameter to return the percentage value
name string yes / Interface name
des string no / Interface description
cancel 'current'/'previous' no / Request abort mode
cache number no / Interface result cache duration milliseconds
urlOnly boolean no / Whether to return only the processed url address (integration params, urlParams)
urlParams object no / url address template replacement mapping
metadata ApiMetadata no / The metadata description of the request parameters is used for d.ts generation and intelligent prompt generation
children Array < API configuration > no [] api configuration nesting
/**
 * Parameter metadata content / Params metadata info
 */
interface ApiMetadataItem {
  /**
   * Parameter name
   * / field name
   */
  name: string
  /**
   * Parameter description
   * / field des
   */
  des: string
  // TODO: parameter verification
  /**
   * Parameter type
   * / field type
   */
  type?: string
  /**
   * Parameter is required
   * / field required
   */
  required?: boolean
  /**
   * Custom verification
   * / field validator
   */
  // validator?:
}

/**
 * Parameter metadata
 */
interface ApiMetadata {
  [index: string]: ApiMetadataItem | string
}

Axios API configuration description

to configure type Default value explain
debug boolean false Show debug log
cacheStorage CacheStorage / Caching tools (such as localStorage, sessionStorage)
interface CacheStorage {
  // Get cache
  getItem(key: string): string | null
  // Set cache
  setItem(key: string, value: string): void
}

Dependency description

"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"
}

Topics: Javascript axios Vue Webpack