-
Notifications
You must be signed in to change notification settings - Fork 395
Expand file tree
/
Copy pathloadJson.ts
More file actions
75 lines (65 loc) · 1.73 KB
/
loadJson.ts
File metadata and controls
75 lines (65 loc) · 1.73 KB
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
import Resource from "terriajs-cesium/Source/Core/Resource";
export default function loadJson<T = any>(
urlOrResource: string | Resource,
headers?: Record<string, unknown>,
body?: any,
asForm: boolean = false
): Promise<T> {
const responseType: XMLHttpRequestResponseType = "json";
let jsonPromise: Promise<T>;
const params: any = {
url: urlOrResource,
headers: headers
};
if (body !== undefined) {
// We need to send a POST
params.headers ??= {};
params.headers["Content-Type"] = "application/json";
if (asForm) {
const data = new FormData();
Object.entries(body).forEach(([key, value]) =>
data.append(key, JSON.stringify(value))
);
params.data = data;
} else {
params.data = JSON.stringify(body);
}
params.responseType = responseType;
jsonPromise =
urlOrResource instanceof Resource
? urlOrResource.post(body, {
responseType: responseType
})!
: Resource.post(params)!;
} else {
// Make a GET instead
jsonPromise =
urlOrResource instanceof Resource
? urlOrResource.fetchJson()!
: Resource.fetchJson(params)!;
}
return jsonPromise;
}
export const loadJsonAbortable = async <T = any>(
urlOrResource: string | Resource,
{
abortSignal,
headers,
body,
asForm = false
}: {
abortSignal: AbortSignal;
headers?: Record<string, unknown>;
body?: any;
asForm?: boolean;
}
) => {
const resource =
urlOrResource instanceof Resource
? urlOrResource
: new Resource({ url: urlOrResource });
abortSignal.addEventListener("abort", () => {
resource.request.cancelFunction();
});
return loadJson<T>(resource, headers, body, asForm);
};