-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathfetchJsonLd.ts
More file actions
88 lines (71 loc) · 2.28 KB
/
Copy pathfetchJsonLd.ts
File metadata and controls
88 lines (71 loc) · 2.28 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
81
82
83
84
85
86
87
88
import type { Document, JsonLd, RemoteDocument } from "jsonld/jsonld-spec.js";
import type { RequestInitExtended } from "../core/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.
* @param {string} url The URL to request.
* @param {RequestInitExtended} [options] Optional fetch options.
* @returns {Promise<ResponseDocument | EmptyResponseDocument>} The response document or an empty response document.
*/
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 };
}
const isJsonContent =
contentType !== null &&
(contentType.includes(jsonLdMimeType) ||
contentType.includes(jsonProblemMimeType));
if (status >= 500 || (!isJsonContent && !response.ok)) {
const reason: RejectedResponseDocument = { response };
// oxlint-disable-next-line no-throw-literal
throw reason;
}
// 2xx response with a content type different from JSON-LD: return empty response
if (!isJsonContent) {
return { response };
}
const body = (await response.json()) as JsonLd;
return {
response,
body,
document: body,
documentUrl: url,
};
}
function setHeaders(options: RequestInitExtended): RequestInit {
if (!options.headers) {
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;
}