/
fetch.client.utils.ts
59 lines (50 loc) · 1.56 KB
/
fetch.client.utils.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
53
54
55
56
57
58
59
import { CommandInstance } from "command";
import { ExtractError } from "types";
// Utils
export const getErrorMessage = (errorCase?: "timeout" | "abort" | "deleted") => {
if (errorCase === "timeout") {
return new Error("Request timeout");
}
if (errorCase === "abort") {
return new Error("Request cancelled");
}
return new Error("Unexpected error");
};
// Responses
export const parseResponse = (response: string | unknown) => {
try {
return JSON.parse(response as string);
} catch (err) {
return response;
}
};
export const parseErrorResponse = <T extends CommandInstance>(response: unknown): ExtractError<T> => {
return response ? parseResponse(response) : getErrorMessage();
};
// Request
export const getUploadSize = (payload: FormData | string) => {
if (payload instanceof FormData) {
return Array.from(payload.values())
.map((value) => (typeof value === "string" ? value.length : value.size))
.reduce((a, b) => a + b, 0);
}
return payload.length;
};
export const fileToBuffer = (file: File | Blob) => {
return new Promise<Uint8Array>((resolve) => {
const reader = new FileReader();
reader.onload = () => {
resolve(new Uint8Array(reader.result as ArrayBufferLike));
};
reader.readAsArrayBuffer(file);
});
};
export const getStreamPayload = (payload: FormData | string | null) => {
if (payload instanceof FormData) {
const parts = Array.from(payload.values()).map((value) =>
typeof value === "string" ? value : fileToBuffer(value),
);
return Promise.all(parts);
}
return payload;
};