-
Notifications
You must be signed in to change notification settings - Fork 101
/
XHRUtils.ts
119 lines (106 loc) · 2.56 KB
/
XHRUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* XHR utils contains public static methods to allow easy access to services via XHR.
*/
export class XHRUtils
{
/**
* Get file data from URL as text, using a XHR call.
*
* @param url - Target for the request.
* @param onLoad - On load callback.
* @param onError - On progress callback.
*/
public static async get(url: string): Promise<any>
{
return new Promise(function(resolve, reject)
{
const xhr = new XMLHttpRequest();
xhr.overrideMimeType('text/plain');
xhr.open('GET', url, true);
xhr.onload = function()
{
resolve(xhr.response);
};
xhr.onerror = reject;
xhr.send(null);
});
}
/**
* Get raw file data from URL, using a XHR call.
*
* @param url - Target for the request.
* @param onLoad - On load callback.
* @param onError - On progress callback.
*/
public static async getRaw(url: string): Promise<ArrayBuffer>
{
return new Promise(function(resolve, reject)
{
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.open('GET', url, true);
xhr.onload = function()
{
resolve(xhr.response);
};
xhr.onerror = reject;
xhr.send(null);
});
}
/**
* Perform a request with the specified configuration.
*
* Syncronous request should be avoided unless they are strictly necessary.
*
* @param url - Target for the request.
* @param type - Resquest type (POST, GET, ...)
* @param header - Object with data to be added to the request header.
* @param body - Data to be sent in the resquest.
* @param onLoad - On load callback, receives data (String or Object) and XHR as arguments.
* @param onError - XHR onError callback.
*/
public static request(url: string, type: string, header?: any, body?: any, onLoad?: Function, onError?: Function, onProgress?: Function): XMLHttpRequest
{
function parseResponse(response): void
{
try
{
return JSON.parse(response);
}
catch (e)
{
return response;
}
}
const xhr = new XMLHttpRequest();
xhr.overrideMimeType('text/plain');
xhr.open(type, url, true);
// Fill header data from Object
if (header !== null && header !== undefined)
{
for (const i in header)
{
xhr.setRequestHeader(i, header[i]);
}
}
if (onLoad !== undefined)
{
xhr.onload = function(event)
{
onLoad(parseResponse(xhr.response), xhr);
};
}
if (onError !== undefined)
{
// @ts-ignore
xhr.onerror = onError;
}
if (onProgress !== undefined)
{
// @ts-ignore
xhr.onprogress = onProgress;
}
xhr.send(body !== undefined ? body : null);
return xhr;
}
}