|
|
|
|
/**
|
|
|
|
|
* https://github.com/jinke18/educoder_weapp
|
|
|
|
|
* @licence GPL-3.0
|
|
|
|
|
* @author jinke18
|
|
|
|
|
*/
|
|
|
|
|
import apiConfig, {baseUrl} from "./apiConfig";
|
|
|
|
|
|
|
|
|
|
export default function ({ name, data:_data = {}, session, success, fail, complete, config:{method,header={}}={}}) {
|
|
|
|
|
let api = apiConfig;
|
|
|
|
|
for (var key of name.split(".")) api=api[key]||console.error(`no api named ${key} in apiList`, api);
|
|
|
|
|
let { url, query={}, form = {}, config:{method:_method,_header={}}={}} = api;
|
|
|
|
|
console.debug(`call EduCoder api ${name}`, api, arguments[0], "require arguments:",form,query);
|
|
|
|
|
if(url){
|
|
|
|
|
url = name.replace(/\.[^\.]*$|\./g, "/") + url.replace(/\{(.*)}/, function (match, k) {
|
|
|
|
|
return _data[k]||console.error(`${k} was not given in data`, _data)
|
|
|
|
|
}).replace(/\*/g,key);
|
|
|
|
|
}else
|
|
|
|
|
url = name.replace(/\./g, "/");
|
|
|
|
|
url = baseUrl + url + ".json";
|
|
|
|
|
method = method||_method;
|
|
|
|
|
header = {..._header,...header};
|
|
|
|
|
var data={},param={};
|
|
|
|
|
if(form._)
|
|
|
|
|
form={...form._,...form[method||"GET"]};
|
|
|
|
|
if(query._)
|
|
|
|
|
query={...query._,...query[method||"GET"]};
|
|
|
|
|
for(var key in form){
|
|
|
|
|
if(key in _data)
|
|
|
|
|
data[key]=_data[key];
|
|
|
|
|
else{
|
|
|
|
|
let value = form[key];
|
|
|
|
|
if (value)
|
|
|
|
|
data[key] = value;
|
|
|
|
|
else if (typeof value == "object")
|
|
|
|
|
console.error(`${key} was not given in data`, _data);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
for(var key in query){
|
|
|
|
|
if (key in _data)
|
|
|
|
|
param[key] = _data[key];
|
|
|
|
|
else {
|
|
|
|
|
let value = query[key];
|
|
|
|
|
if (value)
|
|
|
|
|
param[key] = value;
|
|
|
|
|
else if (typeof value == "object")
|
|
|
|
|
console.error(`${key} was not given in data`, _data);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
let queryStr = Object.keys(param).map(key => `${key}=${param[key]}`).join("&");
|
|
|
|
|
if(queryStr)
|
|
|
|
|
url = url+"?"+queryStr;
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
session.request({
|
|
|
|
|
url, method, data, header,complete,
|
|
|
|
|
success: res => {
|
|
|
|
|
if(res.data.status==1)console.error("!!!api response!!! status===1");
|
|
|
|
|
if (res.data.status&&res.data.status!=1) {
|
|
|
|
|
let e = new Error(res.data.message);
|
|
|
|
|
e.code = res.data.status;
|
|
|
|
|
if (fail) fail(e);
|
|
|
|
|
return reject(e);
|
|
|
|
|
}
|
|
|
|
|
if (success) success(res.data);
|
|
|
|
|
resolve(res.data);
|
|
|
|
|
},
|
|
|
|
|
fail: e => {
|
|
|
|
|
if ("errMsg" in e)
|
|
|
|
|
(e = new Error("(⋟﹏⋞)\n网络连接出错了呢")).code = -1;
|
|
|
|
|
if (!("message" in e))
|
|
|
|
|
(e = new Error("(>_<)\n出现了未知错误")).code = -1;
|
|
|
|
|
console.debug(e);
|
|
|
|
|
if (fail) {fail(e);}
|
|
|
|
|
reject(e);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
})
|
|
|
|
|
}
|