|
1 | 1 | import { parse } from "content-type";
|
2 | 2 |
|
| 3 | +export type CreateTransformOptions = { |
| 4 | + defaultTransform?: (res: Response) => Promise<unknown>; |
| 5 | +}; |
| 6 | + |
3 | 7 | /**
|
4 | 8 | * Takes a fetch response and attempts to transform the response automatically according to the status code and
|
5 | 9 | * Content-Type header (if provided)
|
6 | 10 | * @param response
|
7 | 11 | */
|
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 | + } |
12 | 19 |
|
13 |
| - const contentType = response.headers.get("Content-Type"); |
| 20 | + const contentType = response.headers.get("Content-Type"); |
14 | 21 |
|
15 |
| - if (!contentType) { |
16 |
| - return response.text(); |
17 |
| - } |
| 22 | + if (!contentType) { |
| 23 | + return defaultTransform ? defaultTransform(response) : response.text(); |
| 24 | + } |
18 | 25 |
|
19 |
| - const { type } = parse(contentType); |
| 26 | + const { type } = parse(contentType); |
20 | 27 |
|
21 |
| - switch (type) { |
22 |
| - case "application/json": |
23 |
| - return response.json(); |
| 28 | + switch (type) { |
| 29 | + case "application/json": |
| 30 | + return response.json(); |
24 | 31 |
|
25 |
| - case "text/plain": |
26 |
| - return response.text(); |
| 32 | + case "text/plain": |
| 33 | + return response.text(); |
27 | 34 |
|
28 |
| - default: |
29 |
| - return response.blob(); |
30 |
| - } |
| 35 | + default: |
| 36 | + return defaultTransform ? defaultTransform(response) : response.blob(); |
| 37 | + } |
| 38 | + }; |
31 | 39 | }
|
| 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