Giter Site home page Giter Site logo

saqqdy / axios-ex Goto Github PK

View Code? Open in Web Editor NEW
14.0 3.0 2.0 1.19 MB

A integration solution of axios for large enterprise projects. Support request concurrency control & cancel requests & automatic retry & requests times limit, etc.

Home Page: https://www.saqqdy.com/axios-ex

License: MIT License

TypeScript 94.83% Shell 4.98% JavaScript 0.19%
axios axios-extend axios-ex axios-tool axios-plugin axios-retry

axios-ex's Introduction

axios-ex

A integration solution of axios for large enterprise projects. Support request concurrency control & cancel requests & automatic retry & requests times limit, etc.

NPM version Codacy Badge Test coverage npm download gzip License

Sonar

Read this in other languages: English | 简体中文

Installation

axios-ex comes with the latest version of axios, so you can install it without the axios package

# use pnpm
$ pnpm install axios-ex

# use npm
$ npm install axios-ex --save

# use yarn
$ yarn add axios-ex

Usage

General use

// {app_root}/src/plugins/axios.js
import { getCookie, setCookie } from 'js-cool'
import AxiosExtend from 'axios-ex'

/**
 * Set the request header
 *
 * @param {object} instance AxiosInstance
 */
function setHeaders(instance) {
  instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
}
/**
 * Request Interceptor
 *
 * @param {object} config AxiosRequestConfig
 * @param {object} options request options AxiosExtendRequestOptions
 * @returns AxiosRequestConfig
 */
function onRequest(config, options = {}) {
  // some codes
  return config
}
/**
 * Execute on request error
 *
 * @param {object} err Error
 */
function onRequestError(err) {
  console.error(err)
}
/**
 * Response Interceptor
 *
 * @param {object} res AxiosResponse<any>
 * @param {object} options request options AxiosExtendRequestOptions
 * @returns Promise<unknown>
 */
function onResponse(res, options = {}) {
  if (res.data.success) return res.data
  return Promise.reject(res.data)
}
/**
 * Execute in response error
 *
 * @param {object} err Error
 */
function onResponseError(err) {
  console.error(err)
}
/**
 * Execute on request error & response error
 *
 * @param {object} err Error
 */
function onError(err) {
  console.error(err)
}
/**
 * Request Cancelled
 *
 * @param {object} err Error
 */
function onCancel(err) {
  console.error(err.message)
}

// Instantiation
const axiosEx = new AxiosExtend({
  unique: true, // Whether to cancel the previous similar requests, default: false
  retries: 0, // Number of retries, default: 0, no retries
  orderly: false, // Whether to return in order, default: true
  setHeaders, // function for setting request headers
  onRequest, // Request Interceptor
  onRequestError, // Execute on request error
  onResponse, // Response Interceptor
  onResponseError, // Execute on response error
  onError, // Execute on request error & response error
  onCancel // Callback when request is cancelled
})

export default options => {
  // Here set the unique and orderly priority higher than the instantiation configuration
  options.unique = options.unique ?? false
  options.orderly = options.orderly ?? false
  // Here the unique has a higher priority
  return axiosEx.create(options)
}

Define the delay function for failed retries

  1. Customize the retry delay time

    // Configuration when instantiating
    const axiosEx = new AxiosExtend({
      // ...
      retryDelay: retryCount => {
        return retryCount * 1000
      }
      // ...
    })
  2. Or use axios-ex built-in function, exponentialDelay randomly incremented by 0%-50%

    import AxiosExtend, { exponentialDelay } from 'axios-ex'
    // Configuration when instantiating
    const axiosEx = new AxiosExtend({
      // ...
      retryDelay: exponentialDelay
      // ...
    })

Using with vue2.0

Sometimes we need to use this (vue instance) inside onRequest or onResponse, we can use it like this

import AxiosExtend from 'axios-ex'

let axiosEx = null
// Request Interceptor
function onRequest(config, options = {}) {
  // this => vueInstance
  return config
}
// Response Interceptor
function onResponse(res, options = {}) {
  // hide loading
  if (this instanceof Vue) {
    this.$loader.hide()
  }
  if (res.data.success) return res.data
  return Promise.reject(res.data)
}

export default options => {
  // Only need to initialize once
  if (!axiosEx)
    axiosEx = new AxiosExtend({
      onRequest: onRequest.bind(this),
      onResponse: onResponse.bind(this)
    })

  // show loading
  if (this instanceof Vue) {
    this.$loader.show()
  }
  return axiosEx.create(options)
}

Using unpkg CDN

<script src="https://unpkg.com/[email protected]/dist/index.global.prod.js"></script>

Support & Issues

Please open an issue here.

License

MIT

axios-ex's People

Contributors

dependabot[bot] avatar saqqdy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

nhkyxx nckjxy

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.