jiefancis / blogs

个人博客,学习笔记(issues)
1 stars 0 forks source link

Axios的职责链模式 #30

Open jiefancis opened 2 years ago

jiefancis commented 2 years ago
// 定义Axios类
function Axios(baseOptions = {}) {
    this.interceptors = {
        request: new Interceptor(),
        response: new Interceptor()
    }
    this.baseOptions = baseOptions
}

// 拦截器实现,缓存拦截逻辑
function Interceptor() {
    this.handlers = []
}
Interceptor.prototype.use = function(resolved, rejected) {
    if(!resolved) {
        resolved = config => config
    }
    if(!rejected) {
        rejected = config => config
    }
    this.handlers.push({resolved, rejected})
}

// 执行阶段
// 请求拦截 --> 请求 --> 响应拦截
Axios.prototype.request = function(options) {
    Object.assign(options, this.baseOptions)

    const chain = [function(config) {config.success = true; config.code = 200; console.log('发起请求',config); return config}, err => err]

    this.interceptors.request.handlers.forEach((handler) => {
        chain.unshift(handler.resolved, handler.rejected)
    })
    this.interceptors.response.handlers.forEach((handler) => {
        handler && chain.push(handler.resolved, handler.rejected)
    })

    let promise = Promise.resolve(options)
    while(chain.length) {
        promise = promise.then(chain.shift(), chain.shift())
    }
}

var axios = new Axios({bbll: 2})
axios.interceptors.request.use(function(config) {
    console.log('请求拦截成功', config)
    return config
}, function(config) {
    console.log('请求拦截失败', config)
    return config
})

axios.interceptors.response.use(function(config) {
    console.log('响应拦截成功', config)
    return config
}, function(config) {
    console.log('响应拦截失败', config)
    return config
})

axios.request({url: '1'})