Open chiyan-lin opened 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 } }