import api from "../config/api.js"; import Http from "./Http.js"; import After from "./interceptors/After.js"; import Before from "./interceptors/Before.js"; import Complete from "./interceptors/Complete.js"; import Success from "./interceptors/Success.js"; import Fail from "./interceptors/Fail.js"; import store from "../store"; let Request = { //全局 监听器 和 拦截器 interceptors:function(){ return { after : (new After()).create, before : (new Before()).create, success : (new Success()).create, fail : (new Fail()).create, complete : (new Complete()).create }; }, /** * 获取API接口 * @param {Object} name */ getApi:function(name){ return store.state.http + api[name]; }, /** * get 提交数据 * @param {Object} name api类目 * @param {Object} post 提交参数 * @param {Object} data 其他参数 { type : "json",//默认 返回用json进行解析 header : {key:value},//使用字典模式 传递http头数据 interceptors : { before:()=>{},//请求之前[返回false表示拦击 | 返回true不拦截] after:()=>{},//请求之后 [返回false表示拦击 | 返回true不拦截] success:()=>{},//请求成功 [只能监听] fail:()=>{},//请求失败 [只能监听] complete:()=>{}//无论失败和成功 [只能监听] },//拦截器 | 监听器 //执行顺序 before -> after -> success | fail | complete } * */ get: async function(name,post,data = {}) { return this.build(name,post,"get",data); }, /** * post 提交数据 * @param {Object} name api类目 * @param {Object} post 提交参数 * @param {Object} data 其他参数 参考上面 * */ post: async function(name,post,data = {}) { return this.build(name,post,"post",data); }, /** * 上传文件 * @param {Object} name api类目 * @param {Object} post 提交参数 * @param {Object} post 文件数据 * @param {Object} post 提交input名字 * @param {Object} data 其他参数 参考上面 * */ uploadFile: async function(name,img,inputName,post,data = {}) { return this.build(name,post,"file",data,img,inputName); }, /** * 提交数据 */ build: async function(name,post,method,data = {},img = null,inputName=null){ return await new Promise((resolve, reject) => { let http = new Http(); //类型 if(data.type != null) { http.setType(data.type); } //头部文件 if(data.header != null){ for(var i in data.header) { http.setHeader(i,data.header[i]); } } //全局监听口 let interceptors = this.interceptors(); for(var i in interceptors) { http.interceptors.hasOwnProperty(i) ? http.interceptors[i](interceptors[i]) : ''; } //监听口 if(data.interceptors != null) { for(var i in data.interceptors) { http.interceptors.hasOwnProperty(i) ? http.interceptors[i](data.interceptors[i]) : ''; } } // [成功|失败]返回口 http.interceptors.success((res)=>{ resolve(res); }); //失败返回 http.interceptors.fail((res)=>{ console.log(res); reject(-1,res); }); //监听拦截器,告诉调用口(catch)是否被拦截 http.interceptors._intercept(() =>{ console.log("intercept"); reject(-2); }); var url = ""; if(name.indexOf('http://') == 0 || name.indexOf("https://") == 0) { url = name; } else { url = store.state.http + api[name]; } if(method == 'get') http.get(url,post); if(method == 'post') http.post(url,post); if(method == 'file') http.uploadFile(url,post,img,inputName); }); } }; export default Request;