项目作者: omriLugasi

项目描述 :
Another axios middleware library
高级语言: JavaScript
项目地址: git://github.com/omriLugasi/Redel.git
创建时间: 2019-09-27T15:10:21Z
项目社区:https://github.com/omriLugasi/Redel

开源协议:MIT License

下载


Redel

npm version
install size
npm downloads
license: MIT
Build Status
Coverage Status

A middleware library for promise based axios for the browser and nodeJs

Installing

Using npm:

  1. $ npm install redel

Using yarn:

  1. $ yarn add redel

Redel API

Plugins

Example

Performing a basic usage

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. const config = { log: true }
  4. Redel.use(axios, config)
  5. // ..
  6. axios.get('https://jsonplaceholder.typicode.com/todos')

Performing usage with multiple plugins

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. const config = { log: true, cancel: true, pending: true }
  4. Redel.use(axios, config)
  5. // ..
  6. axios.get('https://jsonplaceholder.typicode.com/todos')

Performing usage with axios.create

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. const axiosInstance = axios.create()
  4. const config = { log: true, cancel: true, pending: true }
  5. Redel.use(axiosInstance, config)
  6. // ..
  7. axiosInstance.get('https://jsonplaceholder.typicode.com/todos')

Cancel Plugin

Cancel plugin is a plugin that wrap your requests
before firing them to the server with axios cancellation functionality.

The cancel plugin work with 2 different functionality:

  1. Single cancel
  2. Cancel by group key

    • Single

      Cancel request that still didn’t return from the server
      when a new request with the same method and pathname
      gonna be fired to the server.

    • Cancel by group key

      Cancel all requests with the unique group key

Usage - Single

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { cancel: true })
  4. let canceledReqeuests = 0
  5. // We can check if the catch function triggered by the Redel cancel plugin
  6. // with the following condition `!!e.isCanceled`
  7. const catchFn = e => {
  8. if (e.isCanceled) {
  9. canceledReqeuests += 1
  10. }
  11. }
  12. const mount = async () => {
  13. const basicUrl = 'https://jsonplaceholder.typicode.com/todos'
  14. await Promise.all([
  15. axios.get(`${basicUrl}?group=3`).catch(catchFn), // canceled
  16. axios.get(`${basicUrl}?group=124`).catch(catchFn), // canceled
  17. axios.get(`${basicUrl}?group=1911`).catch(catchFn), // canceled
  18. axios.get(`${basicUrl}?group=00001`).catch(catchFn) // resolved
  19. ])
  20. console.log({ canceledReqeuests }) // { canceledReqeuests: 3 }
  21. }
  22. mount()

Usage - Cancel by group key

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { cancel: true })
  4. const cancelGroupKey = 'customCancelGroupKey'
  5. const headers = Redel.getCancelGroupHeader(cancelGroupKey)
  6. const basicUrl = 'https://jsonplaceholder.typicode.com/todos'
  7. let canceledReqeuests = 0
  8. // We can check if the catch function triggered by the Redel cancel plugin
  9. // with the following condition `!!e.isCanceled`
  10. const catchFn = e => {
  11. if (e.isCanceled) {
  12. canceledReqeuests += 1
  13. }
  14. }
  15. const mount = () => {
  16. axios.get(`${basicUrl}/1`, { headers }).catch(catchFn),
  17. axios.get(`${basicUrl}/2`, { headers }).catch(catchFn),
  18. axios.get(`${basicUrl}/3`, { headers }).catch(catchFn),
  19. axios.get(`${basicUrl}/4`, { headers }).catch(catchFn)
  20. }
  21. mount()
  22. // beforeDestroyed run the commend below to ensure that
  23. // all pending requests would be canceled
  24. Redel.cancelGroupRequests(cancelGroupKey)

Pending Plugin

Monitoring your pending requests.

Expose functionality to get your pending requests.

Examples

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { pending: true })
  4. axios.get('https://jsonplaceholder.typicode.com/todos/1')
  5. setTimeout(() => {
  6. console.log(Redel.getPendingRequests()) // ["/todos/1"]
  7. })

A common usage of this functionality can be found in “beforeunload”

  1. // if user has any pending request, display warning message
  2. window.addEventListener("beforeunload", function (e) {
  3. if (Redel.getPendingRequests().length) {
  4. // there are pending requests
  5. // display a warning message
  6. }
  7. // unload the page
  8. })

Log Plugin

Monitoring your requests by printing a very informative log about each request.

Examples

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. const url = 'https://jsonplaceholder.typicode.com/todos/1'
  4. Redel.use(axios, { log: true })
  5. axios.get(url)

The above will print the js object below

  1. {
  2. isCompletedWithoutError: true,
  3. maxContentLength: -1,
  4. method: "get",
  5. timeout: 0,
  6. proxy: undefined,
  7. requestData: {query: {}, data: {}, params: {}},
  8. requestHeaders: {
  9. common: {Accept: "application/json", "text/plain": "*/*"},
  10. delete: {},
  11. get: {},
  12. head: {},
  13. patch: {"Content-Type": "application/x-www-form-urlencoded"},
  14. post: {"Content-Type": "application/x-www-form-urlencoded"},
  15. put: {"Content-Type": "application/x-www-form-urlencoded"},
  16. },
  17. responseData: {userId: 1, id: 1, title: "delectus aut autem", completed: false},
  18. endTime: 1571698420250,
  19. startTime: 1571698420167,
  20. totalTime: "83ms",
  21. url: "https://jsonplaceholder.typicode.com/todos/1",
  22. }

Table of content

Property Type Description
isCompletedWithoutError Boolean The request done with error or not
maxContentLength Number Request max content length
method String Request method
timeout number Request time out
proxy object Request proxy
requestData Object Object that hold the request data (data, query, params)
requestHeaders Object Request headers
responseData Object Response data
startTime Number (timestamp) Request start time
endTime Number (timestamp) Request end time
totalTime String Request total time
url String Request url

Use

Work as Redel init function.

To initialize the function we need 2 params, axios and config.

Property Description
axios axios instance
config Contains the desire plugins



The function will sign the plugins into the injected axios instnace.

Example

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { log: true })

add

Add plugin at run time

Example

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { log: true })
  4. // ...
  5. // ...
  6. // ...
  7. Redel.add('cancel')
  8. console.log(Redel.getSignedPlugins()) // ['log', 'cancel']

eject

Remove plugin from Redel.


This is useful when you want to remove specific plugin at run time from the Redel instance.




Example

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { log: true })
  4. //...
  5. //...
  6. //...
  7. console.log(Redel.getSignedPlugins()) // ['log']
  8. Redel.eject('log')
  9. console.log(Redel.getSignedPlugins()) // []

ejectAll

Reset the Redel plugins.


This is useful when you want to remove all your plugins at once.

Note: The axios instance will be saved.

  1. Redel.ejectAll()

getSignedPlugins

Return Array of singed plugins name.

Exmaple

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { log: true, cancel: true })
  4. console.log(Redel.getSignedPlugins()) // ['log', 'cancel']

getPendingRequests

Return Array of string, that each string contain the url of pending request.

Example

  1. const Redel = require('redel')
  2. const axios = require('axios')
  3. Redel.use(axios, { pending: true })
  4. axios.get('https://jsonplaceholder.typicode.com/todos/1')
  5. setTimeout(() => {
  6. console.log(Redel.getPendingRequests()) // ["/todos/1"]
  7. })

clearPendingRequests

Clear the pending request array.

  1. Redel.clearPendingRequests()

cancelGroupRequests

Cancel all requests that belong to the groupKey.

Click here for more information

  1. Redel.cancelGroupRequests('cancelGroupKey')

getCancelGroupHeader

sign request to cancel group.

  1. Redel.getCancelGroupHeader()

You can find examples here