废话少说直接上代码
/**
* Created by Mr.long on 03/15/21.
*/
import service from '../utils/request'
!(function (win, doc) {
/**
* 初始化api对象
* @param obj
*/
function apiSdk(obj) {
this.obj = obj;
}
/**
* apiList
* api列表 可从外部引入 配合 ...展开运算符
* 或者 let apiList = [ ...user, ..config ]
*/
let apiList = [
{
name: 'loginApi',
method: 'post',
url: 'user/api/userLogin'
},
{
name: 'getPetByList',
method: 'get',
url: 'user/api/getPetByList'
},
];
/*获取apiList*/
function getApiList() {
return apiList;
}
/**
*
* @param method 请求方式
* @param data 数据类型
* @param url url
*/
function options(method, data, url) {
const mode = method === "get" ? 'params' : 'data';
return {
method: method,
[mode]: data,
url: url
}
}
/**
*
* @param options {Object} method ? GET params POST data
* @param callback 成功调用的方法
* @param throwOut 失败调用的方法
*/
apiSdk.prototype.api = function (options = {}, callback, throwOut) {
if (options.method !== "") {
if (options.method === 'post' || options.method === 'POST') {
service.post(options.url, options.data).then(res => {
if (typeof callback === 'function') callback(res);
}).catch(err => {
if (typeof throwOut === 'function') throwOut(err);
});
}
if (options.method === 'get' || options.method === 'GET') {
service.get(options.url, {params: options.params}).then(res => {
if (typeof callback === 'function') callback(res);
}).catch(err => {
if (typeof throwOut === 'function') throwOut(err);
})
}
} else {
throw new Error("请输入请求方式")
}
};
/*挂载所有方法到apiSdk上*/
getApiList().map(item => {
return eval("apiSdk.prototype." + item.name + "= function (param, callback, throwOut) {\n" +
" return this.api(options(item.method, param, item.url), callback, throwOut);\n" +
"};");
});
/*挂载到win环境上*/
win.JSsdk = new apiSdk();
/*使用完整实例*/
/*JSsdk.loginApi({userName: 2380160312, userPass: 'd0970714757783e6cf17b26fb8e2298f'},(res)=>{
console.log(res)
}),(err)=>{
console.log(err)
}*/
})(window, document);