-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathfetch.ts
More file actions
68 lines (62 loc) · 2 KB
/
Copy pathfetch.ts
File metadata and controls
68 lines (62 loc) · 2 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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { HttpRequest, HttpResponse, HttpTransferOptions } from '../types/http';
import { TransferHandler } from '../types/core';
import { AmplifyError } from '../../errors';
import { withMemoization } from '../utils/memoization';
import { AmplifyErrorCode } from '../../types';
const shouldSendBody = (method: string) =>
!['HEAD', 'GET'].includes(method.toUpperCase());
// TODO[AllanZhengYP]: we need to provide isCanceledError utility
export const fetchTransferHandler: TransferHandler<
HttpRequest,
HttpResponse,
HttpTransferOptions
> = async (
{ url, method, headers, body },
{ abortSignal, cache, withCrossDomainCredentials },
) => {
let resp: Response;
try {
resp = await fetch(url, {
method,
headers,
body: shouldSendBody(method) ? body : undefined,
signal: abortSignal,
cache,
credentials: withCrossDomainCredentials ? 'include' : 'same-origin',
});
} catch (e) {
if (e instanceof Error && e.name === 'AbortError') {
throw e;
}
// Fetch only rejects for aborts and network failures. HTTP error responses resolve
// normally. Browsers typically throw TypeError, while React Native throws Error
// objects for network failures.
throw new AmplifyError({
name: AmplifyErrorCode.NetworkError,
message: 'A network error has occurred.',
underlyingError: e,
});
}
const responseHeaders: Record<string, string> = {};
resp.headers?.forEach((value: string, key: string) => {
responseHeaders[key.toLowerCase()] = value;
});
const httpResponse = {
statusCode: resp.status,
headers: responseHeaders,
body: null,
};
// resp.body is a ReadableStream according to Fetch API spec, but React Native
// does not implement it.
const bodyWithMixin = Object.assign(resp.body ?? {}, {
text: withMemoization(() => resp.text()),
blob: withMemoization(() => resp.blob()),
json: withMemoization(() => resp.json()),
});
return {
...httpResponse,
body: bodyWithMixin,
};
};