Skip to content

Commit

Permalink
refactor(http-utils): Refactor download progress handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
junhaoliao committed Feb 7, 2025
1 parent 60c476b commit 8b955cb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/services/LogFileManager/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ const loadFile = async (fileSrc: FileSrcType)
let fileData: Uint8Array;
if ("string" === typeof fileSrc) {
fileName = getBasenameFromUrlOrDefault(fileSrc);
fileData = await getUint8ArrayFrom(fileSrc, () => null);
fileData = await getUint8ArrayFrom(fileSrc);
} else {
fileName = fileSrc.name;
fileData = new Uint8Array(await fileSrc.arrayBuffer());
Expand Down
38 changes: 28 additions & 10 deletions src/utils/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import axios, {AxiosError} from "axios";
import axios, {
AxiosError,
AxiosProgressEvent,
} from "axios";


type ProgressCallback = (numBytesDownloaded:number, numBytesTotal:number) => void;
Expand Down Expand Up @@ -32,25 +35,41 @@ const convertAxiosError = (e: AxiosError): Error => {
);
};


/**
* Normalizes the total size of a download event, and calls the provided onProgress callback with
* loaded and total sizes.
*
* @param onProgress
* @return The handler that wraps `onProgress`.
*/
const normalizeTotalSize = (onProgress: ProgressCallback) => ({
loaded,
total,
}: AxiosProgressEvent) => {
if ("undefined" === typeof total || isNaN(total)) {
total = loaded;
}
onProgress(loaded, total);
};

/**
* Downloads (bypassing any caching) a file as a Uint8Array.
*
* @param fileUrl
* @param progressCallback
* @param [onProgress]
* @return The file's content.
* @throws {Error} if the download fails.
*/
const getUint8ArrayFrom = async (fileUrl: string, progressCallback: ProgressCallback)
const getUint8ArrayFrom = async (
fileUrl: string,
onProgress: ProgressCallback = () => null
)
: Promise<Uint8Array> => {
try {
const {data} = await axios.get<ArrayBuffer>(fileUrl, {
responseType: "arraybuffer",
onDownloadProgress: ({loaded, total}) => {
if ("undefined" === typeof total) {
total = loaded;
}
progressCallback(loaded, total);
},
onDownloadProgress: normalizeTotalSize(onProgress),
headers: {
"Cache-Control": "no-cache",
"Pragma": "no-cache",
Expand All @@ -66,5 +85,4 @@ const getUint8ArrayFrom = async (fileUrl: string, progressCallback: ProgressCall
}
};


export {getUint8ArrayFrom};

0 comments on commit 8b955cb

Please sign in to comment.