/
services.ts
319 lines (267 loc) · 10.5 KB
/
services.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import { blockUI, blockUndo } from "./blockui";
import { Config } from "./config";
import { getjQuery } from "./environment";
import { ErrorHandling } from "./errorhandling";
import { RequestErrorInfo, ServiceOptions, ServiceResponse } from "./servicetypes";
export function resolveUrl(url: string) {
if (url != null && url.charAt(0) == '~' && url.charAt(1) == '/')
return Config.applicationPath + url.substring(2);
return url;
}
export function resolveServiceUrl(url: string) {
if (url && url.length && url.charAt(0) != '~' && url.charAt(0) != '/' && url.indexOf('://') < 0)
return resolveUrl("~/Services/") + url;
return resolveUrl(url);
}
export function getCookie(name: string) {
let $ = getjQuery();
if (typeof $?.cookie === "function")
return $.cookie(name);
name += '=';
for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--)
if (!ca[i].indexOf(name))
return ca[i].replace(name, '');
}
export function isSameOrigin(url: string) {
var loc = window.location,
a = document.createElement('a');
a.href = url;
return a.hostname == loc.hostname &&
a.port == loc.port &&
a.protocol == loc.protocol;
}
function serviceOptions<TResponse>(url: string, options: ServiceOptions<TResponse>) {
options = Object.assign(<ServiceOptions<TResponse>>{
allowRedirect: true,
async: true,
blockUI: true,
method: 'POST',
}, options);
options.headers ??= {};
options.headers["Accept"] ??= "application/json";
options.headers["Content-Type"] ??= "application/json";
if (isSameOrigin(url)) {
var token = getCookie('CSRF-TOKEN');
if (token)
options.headers["X-CSRF-TOKEN"] = token;
}
return options;
}
let activeRequests: number = 0;
export function requestStarting() {
activeRequests++;
let $ = getjQuery();
if ($ && typeof $.active === "number") {
($.active++ === 0) && $.event?.trigger?.("ajaxStart");
}
else if (activeRequests === 1) {
typeof document !== "undefined" && document.dispatchEvent(new Event("ajaxStart"));
}
}
export function requestFinished() {
activeRequests--;
let $ = getjQuery();
if ($ && typeof $.active === "number") {
!(--$.active) && $.event?.trigger?.("ajaxStop");
}
else if (!activeRequests) {
typeof document !== "undefined" && document.dispatchEvent(new Event("ajaxStop"));
}
}
export function getActiveRequests() {
return activeRequests;
}
function serviceFetch<TResponse extends ServiceResponse>(options: ServiceOptions<TResponse>): Promise<TResponse> {
if (typeof fetch !== "function")
return Promise.reject(reason("The fetch method is not available!", "fetch-missing"));
return (async function () {
let url = options.service ? resolveServiceUrl(options.service) : resolveUrl(options.url);
options = serviceOptions(url, options);
requestStarting();
try {
options.blockUI && blockUI();
try {
let {
allowRedirect: _1,
async: _2,
blockUI: _3,
request: _4,
service: _5,
url: _6,
onCleanup: _7,
onError: _8,
onSuccess: _9,
...fetchInit
} = options;
fetchInit.body = JSON.stringify(options.request);
var fetchResponse = await fetch(url, fetchInit);
if (!fetchResponse.ok) {
await handleFetchError(fetchResponse, options);
return Promise.reject(reason(`Service fetch to '${url}' resulted in HTTP ${fetchResponse.status} error: ${fetchResponse.statusText}!`,
"http-error", { fetchResponse, url }));
}
let response = await fetchResponse.json() as TResponse;
if (!response)
return Promise.reject(reason(`Received empty response from service fetch to '${url}'!`,
"empty-response", { fetchResponse, url }));
if (response.Error) {
handleError(response ?? {}, { status: fetchResponse.status, statusText: fetchResponse.statusText }, options);
return Promise.reject(reason(`Service fetch to '${url}' resulted in error: ${response.Error.Message ?? response.Error.Code}!`,
"service-error", { response, fetchResponse, url }));
}
options.onSuccess?.(response);
return response;
}
finally {
options.blockUI && blockUndo();
options.onCleanup && options.onCleanup();
}
}
finally {
requestFinished();
}
})();
}
function reason(message: string, kind: string, extra?: any) {
var error: Error;
if (extra?.cause != null) {
error = (Error as any)(message, { cause: extra.cause });
}
else {
error = Error(message);
}
if (kind != null) {
(error as any).kind = kind;
}
(error as any).origin = "serviceCall";
if (extra != null) {
if ((error as any).cause)
delete extra.cause;
Object.assign(error, extra);
}
return error;
}
export function serviceCall<TResponse extends ServiceResponse>(options: ServiceOptions<TResponse>): PromiseLike<TResponse> {
if (options?.async ?? true)
return serviceFetch(options);
let url: string;
return new Promise((resolve, reject) => {
try {
url = options.service ? resolveServiceUrl(options.service) : resolveUrl(options.url);
options = serviceOptions(url, options);
var xhr = new XMLHttpRequest();
xhr.open(options.method, url, false);
if (options.cache == "no-store")
options.headers["Cache-Control"] ??= "no-cache, no-store, max-age=0";
else if (options.cache === "no-cache")
options.headers["Cache-Control"] ??= "no-cache";
for (var x in options.headers) {
xhr.setRequestHeader(x, options.headers[x]);
}
requestStarting();
try {
if (options.signal) {
options.signal.addEventListener("abort", () => {
xhr.abort();
}, { once: true });
}
xhr.send(JSON.stringify(options.request));
try {
if (xhr.status !== 200) {
handleXHRError(xhr, options);
return reject(reason(`HTTP ${xhr.status} error on service call to '${url}': ${xhr.statusText}!`,
"http-error", { status: xhr.status, statusText: xhr.statusText, url }));
}
let response = JSON.parse(xhr.responseText) as TResponse;
if (!response)
return reject(reason(`Empty response received on service call to '${url}'!`,
"empty-response", { url }));
if (response.Error) {
handleError(response, { status: xhr.status, statusText: xhr.statusText }, options);
return reject(reason(`Service call to '${url}' resulted in error: ${response.Error.Message ?? response.Error.Code}!`,
"service-error", { response, url }));
}
options.onSuccess?.(response);
return resolve(response);
}
finally {
options.blockUI && blockUndo();
options.onCleanup && options.onCleanup();
}
}
finally {
requestFinished();
}
}
catch (exception) {
reject(reason(`Service call to '${url}' thrown exception: ${exception.toString()}`,
"exception", { cause: exception, url }));
}
});
}
export function serviceRequest<TResponse extends ServiceResponse>(service: string, request?: any,
onSuccess?: (response: TResponse) => void, options?: ServiceOptions<TResponse>): PromiseLike<TResponse> {
return serviceCall(Object.assign({
service: service,
request: request,
onSuccess: onSuccess
}, options));
}
function handleError(response: any, errorInfo: RequestErrorInfo, options: ServiceOptions<any>) {
if (Config.notLoggedInHandler != null &&
response &&
response.Error &&
response.Error.Code == 'NotLoggedIn' &&
Config.notLoggedInHandler(options, response)) {
return;
}
if (options?.onError?.(response, errorInfo) ||
options?.errorMode === 'none')
return;
ErrorHandling.showServiceError(response?.Error, errorInfo, options?.errorMode);
};
function handleRedirect(getHeader: (key: string) => string): boolean {
var l: any = null;
try {
l = getHeader('Location');
}
catch ($t1) {
l = null;
}
if (l) {
window.top.location.href = l;
return true;
}
}
async function handleFetchError(response: Response, options: ServiceOptions<any>): Promise<void> {
if (response.status === 403 && options.allowRedirect && handleRedirect(response.headers.get))
return;
if ((response.headers.get('content-type') || '').toLowerCase().indexOf('json') >= 0) {
var json = (await response.json()) as ServiceResponse;
if (json && json.Error) {
handleError(json, {
status: response.status,
statusText: response.statusText
}, options);
return;
}
}
handleError(null, {
status: response.status,
statusText: response.statusText,
responseText: await response.text()
}, options);
}
function handleXHRError(xhr: XMLHttpRequest, options: ServiceOptions<any>) {
if (xhr.status === 403 && options.allowRedirect && handleRedirect(xhr.getResponseHeader))
return;
if ((xhr.getResponseHeader('content-type') || '')
.toLowerCase().indexOf('application/json') >= 0) {
var json = JSON.parse(xhr.responseText);
if (json && json.Error) {
handleError(json, { status: xhr.status, statusText: xhr.statusText }, options);
return;
}
}
handleError(null, { status: xhr.status, statusText: xhr.statusText, responseText: xhr.responseText }, options);
}