依赖Jquery,主要使用了jquery的$.Callbacks
'use strict'
class Http {
constructor() {
this._init();
}
_init() {
this._initInterceptors();
}
_initConfig(config) {
this.defaultConfig = {
async: true,
method: 'GET',
dataType: 'json'
};
Object.assign(config, this.defaultConfig);
}
_initInterceptors() {
const that = this;
this.requestInterceptors = {
done: $.Callbacks('once stopOnFalse'),
fail: $.Callbacks('once stopOnFalse')
}
this.responseInterceptors = {
done: $.Callbacks('once stopOnFalse'),
fail: $.Callbacks('once stopOnFalse')
}
this.interceptors = {
request:{
use: (success, fail)=>{
that._requestUse.call(that, success, fail);
return that.interceptors.request;
}
},
response: {
use: (success, fail)=>{
that._responseUse.call(that, success, fail);
return that.interceptors.response;
}
}
}
}
_addReuestToInterceptors(config) {
console.log(this.requestInterceptors.done)
this.requestInterceptors['done'].add(
config =>{
this._realRequestFun(config);
}
);
this.requestInterceptors['done'].fire(config);
}
send(config) {
this._initConfig(config);
this._addReuestToInterceptors(config);
}
_requestUse(success, fail) {
if (success != undefined && Object.prototype.toString.call(success) === '[object Function]') {
this.requestInterceptors['done'].add(success);
}
if (fail != undefined && Object.prototype.toString.call(fail) === '[object Function]') {
this.requestInterceptors['fail'].add(fail);
}
}
_responseUse(success, fail) {
if (success != undefined && Object.prototype.toString.call(success) === '[object Function]') {
this.responseInterceptors['done'].add(success);
}
if (fail != undefined && Object.prototype.toString.call(fail) === '[object Function]') {
this.responseInterceptors['fail'].add(fail);
}
}
_realRequestFun(config) {
const that = this;
let deferred = $.Deferred();
$.when(
that._await(deferred, config)
).done(res => {
that.responseInterceptors['done'].fire(res);
}).fail(err => {
that.responseInterceptors['fail'].fire(err);
})
}
_await (deferred, config) {
$.ajax(config)
.done(data => {
deferred.resolve(data);
})
.fail(err => {
deferred.reject(err);
})
return deferred.promise();
}
}
例子
let http = new Http();
http.interceptors.request.use(config =>{
console.log(1)
},err =>{
console.log(err)
}).use(config =>{
console.log(2)
})
http.interceptors.response.use(data =>{
console.log("+++++++")
console.log(data)
console.log("+++++++")
},err =>{
console.log(err)
})
http.send({
type: "GET",
url: "",
dataType: 'json',
data: {
//
}
})
拦截函数返回的false将中断拦截
let http = new Http();
http.interceptors.request.use(config =>{
console.log(1)
return false
},err =>{
console.log(err)
}).use(config =>{
console.log(2)
})
http.interceptors.response.use(data =>{
console.log("+++++++")
console.log(data)
console.log("+++++++")
},err =>{
console.log(err)
})
http.send({
type: “GET”,
url:"",
dataType: ‘json’,
data: {
//
}
})