import apiConfig, {baseUrl} from "./apiConfig"; function handler({success, fail, resolve, reject}){ return { success: res => { if (res.data.status <=100 ) console.error("!!!api response!!! status==="+res.data.status); if (res.data.status && res.data.status > 100 || res.data.status<0) { switch (res.data.status) { case 401: var message = "(●'◡'●)\n请先登录哦"; var code = res.data.status; break; default: var message = res.data.message; var code = res.data.status; } let e = new Error(message); e.code = code; if (fail) fail(e); return reject(e); } if (success) success(res.data); resolve(res.data); }, fail: e => { console.error(e); if ("errMsg" in e) (e = new Error("(⋟﹏⋞)\n网络连接出错了呢")).code = -2; if (!("message" in e)) (e = new Error("(>_<)\n出现了未知错误")).code = -1; console.debug(e); if (fail) { fail(e); } reject(e); } } } 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={},...config}={}} = api; method = method || _method; console.debug(`call EduCoder api ${name}`, api, arguments[0], "require arguments:",form,query); if(url){ if(url._) url = url[method||"GET"]; 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"; 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!=null) 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!=null) 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; if(method=="uploadFile"){ console.log("uploadFile") var formData = data; var {name:_name, timeout} = config; if(!_name) _name = Object.keys(formData)[0]; var filePath = formData[_name]; delete formData[_name]; console.log({ url, filePath, name: _name, header, timeout, formData}); return new Promise((resolve, reject)=>{ session.uploadFile({ url, filePath, name:_name, header, timeout, formData,complete, ...handler({success, fail, resolve, reject}) }) }); }else return new Promise((resolve, reject) => { session.request({ url, method, data, header,complete,...handler({success, fail, resolve, reject}) }); }) }