-
-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathfetchJsonLd.ts
More file actions
59 lines (47 loc) · 1.46 KB
/
fetchJsonLd.ts
File metadata and controls
59 lines (47 loc) · 1.46 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
import { Document } from "jsonld/jsonld-spec";
import { RequestInitExtended } from "./types";
const jsonLdMimeType = "application/ld+json";
/**
* Sends a JSON-LD request to the API.
*/
export default async function fetchJsonLd(
url: string,
options: RequestInitExtended = {}
): Promise<{
response: Response;
body?: Document;
document?: Document;
}> {
const response = await fetch(url, setHeaders(options));
const { headers, status } = response;
const contentType = headers.get("Content-Type");
if ([202, 204].includes(status)) {
return Promise.resolve({ response });
}
if (500 <= status || !contentType || !contentType.includes(jsonLdMimeType)) {
return Promise.reject({ response });
}
return response
.json()
.then((body: Document) => ({ response, body, document: body }));
}
function setHeaders(options: RequestInitExtended): RequestInit {
if (!options.headers) {
return { ...options, headers: {} };
}
let headers: HeadersInit =
typeof options.headers === "function" ? options.headers() : options.headers;
headers = new Headers(headers);
if (null === headers.get("Accept")) {
headers.set("Accept", jsonLdMimeType);
}
const result = { ...options, headers };
if (
"undefined" !== result.body &&
!(typeof FormData !== "undefined" && result.body instanceof FormData) &&
null === result.headers.get("Content-Type")
) {
result.headers.set("Content-Type", jsonLdMimeType);
}
return result;
}