-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
FetchInitPreprocessor-browser.ts
52 lines (45 loc) 路 1.83 KB
/
FetchInitPreprocessor-browser.ts
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
/* eslint-disable unicorn/filename-case */
/* eslint-enable unicorn/filename-case */
import { ActorHttp } from '@comunica/bus-http';
import type { IFetchInitPreprocessor } from './IFetchInitPreprocessor';
/**
* Overrides things for fetch requests in browsers
*/
export class FetchInitPreprocessor implements IFetchInitPreprocessor {
public async handle(init: RequestInit): Promise<RequestInit> {
// Remove overridden user-agent header within browsers to avoid CORS issues
if (init.headers) {
const headers = new Headers(init.headers);
if (headers.has('user-agent')) {
headers.delete('user-agent');
}
init.headers = headers;
}
// TODO: remove this workaround once this has a fix: https://github.com/inrupt/solid-client-authn-js/issues/1708
if (init?.headers && 'append' in init.headers) {
init.headers = ActorHttp.headersToHash(init.headers);
}
// Browsers don't yet support passing ReadableStream as body to requests, see
// https://bugs.chromium.org/p/chromium/issues/detail?id=688906
// https://bugzilla.mozilla.org/show_bug.cgi?id=1387483
// As such, we convert those bodies to a plain string
// TODO: remove this once browser support ReadableStream in requests
if (init.body && typeof init.body !== 'string' && 'getReader' in init.body) {
const reader = init.body.getReader();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
chunks.push(value);
}
init.body = chunks.join('');
}
// Only enable keepalive functionality if we are not sending a body (some browsers seem to trip over this)
return { keepalive: !init.body, ...init };
}
public async createAbortController(): Promise<AbortController> {
return new AbortController();
}
}