2019-11-04 12:19:50 +00:00
|
|
|
import '@ms/api'
|
|
|
|
|
2020-02-29 14:28:43 +00:00
|
|
|
const URL = Java.type('java.net.URL')
|
|
|
|
const Paths = Java.type('java.nio.file.Paths');
|
|
|
|
const Files = Java.type('java.nio.file.Files');
|
|
|
|
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption');
|
|
|
|
|
2019-11-04 12:19:50 +00:00
|
|
|
export type Method =
|
|
|
|
| 'get' | 'GET'
|
|
|
|
| 'delete' | 'DELETE'
|
|
|
|
| 'head' | 'HEAD'
|
|
|
|
| 'options' | 'OPTIONS'
|
|
|
|
| 'post' | 'POST'
|
|
|
|
| 'put' | 'PUT'
|
|
|
|
| 'patch' | 'PATCH'
|
|
|
|
|
|
|
|
interface RequestConfig {
|
|
|
|
url?: string;
|
|
|
|
method?: Method;
|
|
|
|
headers?: { [key: string]: string };
|
|
|
|
params?: { [key: string]: string };
|
|
|
|
data?: any;
|
2019-09-07 04:23:15 +00:00
|
|
|
}
|
|
|
|
|
2019-11-04 12:19:50 +00:00
|
|
|
function request(config: RequestConfig) {
|
2020-02-01 17:58:07 +00:00
|
|
|
// @ts-ignore
|
2019-11-04 12:19:50 +00:00
|
|
|
let xhr = new XMLHttpRequest();
|
|
|
|
xhr.open(config.method, config.url, false);
|
|
|
|
for (const header in config.headers) {
|
|
|
|
xhr.setRequestHeader(header, config.headers[header]);
|
2019-09-07 04:23:15 +00:00
|
|
|
}
|
2020-02-23 14:33:51 +00:00
|
|
|
xhr.send(config.data);
|
|
|
|
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
|
|
|
|
xhr.responseType = "json"
|
|
|
|
}
|
|
|
|
return xhr.get();
|
2019-09-07 04:23:15 +00:00
|
|
|
}
|
|
|
|
|
2020-02-29 14:28:43 +00:00
|
|
|
function download(url: string, target: string) {
|
|
|
|
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
|
|
|
|
}
|
|
|
|
|
2019-11-04 12:19:50 +00:00
|
|
|
function _proxy(method: Method) {
|
2020-02-29 14:28:43 +00:00
|
|
|
return function (url: string, data?: any, config?: RequestConfig) {
|
2019-11-04 12:19:50 +00:00
|
|
|
return request({ url, method, data, ...config });
|
2019-09-07 04:23:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-04 12:19:50 +00:00
|
|
|
export default {
|
|
|
|
get: _proxy('GET'),
|
|
|
|
post: _proxy('POST'),
|
2020-02-29 14:28:43 +00:00
|
|
|
request,
|
|
|
|
download
|
2019-09-07 04:23:15 +00:00
|
|
|
}
|