chiyan-lin / Blog

welcome gaidy Blog
6 stars 3 forks source link

利用中间件实现axios封装请求 #4

Open chiyan-lin opened 4 years ago

chiyan-lin commented 4 years ago

import Axios from 'axios'

// 中间件执行函数
function createMiddlewareChain(
  middleware,
  request,
  ctx
) {
  return middleware.reduce(
    (acc, middleware) => {
      return async function() {
        await middleware(ctx, acc)
      }
    },
    request
  )
}

class Requester {
  middlewareList = []
  axios = null

  constructor({ config = {} } = {}) {
    this.middlewareList = []
    this.axios = Axios.create(config)
  }

  addMiddleWare(middleWare) {
    return this.addMiddleware(middleWare)
  }

  addMiddleware(middleware) {
    this.middlewareList.unshift(middleware)
    return this
  }

  getMiddlewareList() {
    return this.middlewareList
  }

  sendRequest(
    config,
    ctx
  ) {
    return async () => {
      const response = await this.axios.request(config)
      ctx.response = response
    }
  }

  async request(
    config,
    context
  ) {
    const ctx = {
      ...context,
      request: config,
      response: null
    }
    const chain = createMiddlewareChain(
      this.getMiddlewareList(),
      this.sendRequest(config, ctx),
      ctx
    )
    await chain()

    return ctx.response
  }
}