Skip to content

Commit 0347ef3

Browse files
Checking new transform setup
1 parent 4349ba7 commit 0347ef3

File tree

1 file changed

+33
-17
lines changed

1 file changed

+33
-17
lines changed
Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,47 @@
11
import { parse } from "content-type";
22

3+
export type CreateTransformOptions = {
4+
defaultTransform?: (res: Response) => Promise<unknown>;
5+
};
6+
37
/**
48
* Takes a fetch response and attempts to transform the response automatically according to the status code and
59
* Content-Type header (if provided)
610
* @param response
711
*/
8-
export default function transform(response: Response) {
9-
if (response.status === 204) {
10-
return Promise.resolve(null);
11-
}
12+
export function createTransform({
13+
defaultTransform,
14+
}: CreateTransformOptions = {}) {
15+
return (response: Response) => {
16+
if (response.status === 204) {
17+
return Promise.resolve(null);
18+
}
1219

13-
const contentType = response.headers.get("Content-Type");
20+
const contentType = response.headers.get("Content-Type");
1421

15-
if (!contentType) {
16-
return response.text();
17-
}
22+
if (!contentType) {
23+
return defaultTransform ? defaultTransform(response) : response.text();
24+
}
1825

19-
const { type } = parse(contentType);
26+
const { type } = parse(contentType);
2027

21-
switch (type) {
22-
case "application/json":
23-
return response.json();
28+
switch (type) {
29+
case "application/json":
30+
return response.json();
2431

25-
case "text/plain":
26-
return response.text();
32+
case "text/plain":
33+
return response.text();
2734

28-
default:
29-
return response.blob();
30-
}
35+
default:
36+
return defaultTransform ? defaultTransform(response) : response.blob();
37+
}
38+
};
3139
}
40+
41+
export const transformDefaultJson = createTransform({
42+
defaultTransform: (response) => response.json(),
43+
});
44+
45+
const transform = createTransform();
46+
47+
export default transform;

0 commit comments

Comments
 (0)