-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajaxHelper.js
78 lines (72 loc) · 2.34 KB
/
ajaxHelper.js
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
// File: ajaxHelper.js
export async function makeAjaxRequest(url, method, headers, data, onSuccess, onError, memo) {
if (method === "GET") {
// Try to get the response from the cache
const cache = await caches.open('classification-cache');
const cachedResponse = await cache.match(url);
if (cachedResponse) {
// If the response is in the cache, use it
onSuccess(await cachedResponse.json());
} else {
// If the response is not in the cache, fetch it
try {
const response = await fetch(url, { headers });
const contentType = response.headers.get("content-type");
if (contentType && (contentType.includes("application/json") || contentType.includes("application/sparql-results+json"))) {
const data = await response.json();
try {
cache.put(url, new Response(JSON.stringify(data), response));
} catch (cacheError) {
console.error('Caching failed:', cacheError);
}
onSuccess(data);
} else {
$("#spinner").hide();
const responseText = await response.text();
const errMessage = `Response is not JSON [ref: ${memo}]
Response text: ${responseText}`;
document.getElementById('errorContainer').innerText = errMessage;
throw new Error(errMessage); // Reject promise with error
}
} catch (error) {
onError(error);
}
}
} else {
// For non-GET requests, use jQuery's $.ajax method
$.ajax({
url: url,
method: method,
headers: headers,
data: data,
success: onSuccess,
error: onError
});
}
}
/**
* Class to manage and limit the number of concurrent asynchronous requests (promises) that are executed at the same time.
*/
export class RequestQueue {
constructor(maxConcurrent) {
this.queue = [];
this.activeCount = 0;
this.maxConcurrent = maxConcurrent;
}
add(promiseFn) {
return new Promise((resolve, reject) => {
this.queue.push(() => promiseFn().then(resolve).catch(reject));
this.next();
});
}
next() {
if (this.activeCount < this.maxConcurrent && this.queue.length > 0) {
const promiseFn = this.queue.shift();
this.activeCount++;
promiseFn().finally(() => {
this.activeCount--;
this.next();
});
}
}
}