2022-11-03 16:34:58 +08:00

73 lines
2.4 KiB
TypeScript

import WuhuBase from "../WuhuBase";
import Log from "../Log";
import AjaxFetchOption from "../../interface/AjaxFetchOption";
import IUserProfileData from "../../interface/IUserProfileData";
export default class FetchUtils extends WuhuBase {
className = 'FetchUtils';
/**
* 包装jquery ajax 异步返回string
* @param url
* @param method
*/
public ajax(url: string, method: 'GET' | 'POST'): Promise<string> {
return new Promise((res, rej) => {
$.ajax({
method: method,
url: url,
success: function (data) {
res(data)
},
error: function (e) {
rej(e)
}
});
});
}
public ajaxFetch(opt: AjaxFetchOption) {
let { url, referrer = '/', method, body = null } = opt;
let req_params: RequestInit = {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
referrer,
method,
};
if (method === 'POST') {
req_params.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
req_params.body = body;
}
return window.fetch(url, req_params);
}
public fetchText(url: string, init: RequestInit = null): Promise<string> {
return new Promise((resolve, reject) =>
window.fetch(url, init)
.then(res => res.text())
.then(t => resolve(t))
.catch(err => {
Log.error('fetchText出错了', err);
reject(err);
})
);
}
public getProfile(uid: string): Promise<IUserProfileData> {
return new Promise((resolve, reject) => {
this.ajaxFetch({
url: window.addRFC('https://www.torn.com/profiles.php?step=getProfileData&XID=' + uid),
method: 'GET'
}).then((o) => {
o.json().then((res) => {
resolve(res);
}).catch(e => {
Log.error('[ProfileHelper] JSON解析错误: ', e.message, '错误堆栈: ', e.stack);
reject(e);
});
}).catch(e => {
Log.error('[ProfileHelper] 网络错误: ', e.message, '错误堆栈: ', e.stack);
reject(e);
});
});
}
}