-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathfetchJsonLd.ts
More file actions
80 lines (65 loc) · 1.88 KB
/
fetchJsonLd.ts
File metadata and controls
80 lines (65 loc) · 1.88 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
76
77
78
79
80
import type { Document, JsonLd, RemoteDocument } from "jsonld/jsonld-spec.js";
import type { RequestInitExtended } from "../types.js";
const jsonLdMimeType = "application/ld+json";
const jsonProblemMimeType = "application/problem+json";
interface RejectedResponseDocument {
response: Response;
}
interface EmptyResponseDocument {
response: Response;
}
interface ResponseDocument extends RemoteDocument {
response: Response;
body: Document;
}
/**
* Sends a JSON-LD request to the API.
*/
export default async function fetchJsonLd(
url: string,
options: RequestInitExtended = {},
): Promise<ResponseDocument | EmptyResponseDocument> {
const response = await fetch(url, setHeaders(options));
const { headers, status } = response;
const contentType = headers.get("Content-Type");
if (status === 204) {
return { response };
}
if (
status >= 500 ||
!contentType ||
(!contentType.includes(jsonLdMimeType) &&
!contentType.includes(jsonProblemMimeType))
) {
const reason: RejectedResponseDocument = { response };
// oxlint-disable-next-line no-throw-literal
throw reason;
}
const body = (await response.json()) as JsonLd;
return {
response,
body,
document: body,
documentUrl: url,
};
}
function setHeaders(options: RequestInitExtended): RequestInit {
if (!options.headers) {
return { ...options, headers: {} };
}
let headers =
typeof options.headers === "function" ? options.headers() : options.headers;
headers = new Headers(headers);
if (headers.get("Accept") === null) {
headers.set("Accept", jsonLdMimeType);
}
const result = { ...options, headers };
if (
result.body !== "undefined" &&
!(typeof FormData !== "undefined" && result.body instanceof FormData) &&
result.headers.get("Content-Type") === null
) {
result.headers.set("Content-Type", jsonLdMimeType);
}
return result;
}