Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(utils): Add support for fetching remote JSON objects. #178

Merged
merged 11 commits into from
Feb 17, 2025
31 changes: 29 additions & 2 deletions src/utils/http.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import axios, {AxiosError} from "axios";

import {JsonValue} from "../typings/js";


/**
* Converts an Axios error into a custom Error object.
Expand Down Expand Up @@ -30,6 +32,29 @@ const convertAxiosError = (e: AxiosError): Error => {
);
};

/**
* Downloads and parses JSON from the specified remote URL.
*
* @param remoteUrl
* @return The parsed response. If the HTTP response body is not JSON, the body is gracefully
* returned as a string.
* @throws {Error} if the download fails.
*/
const getJsonObjectFrom = async (remoteUrl: string)
: Promise<JsonValue> => {
try {
const {data} = await axios.get<JsonValue>(remoteUrl, {
responseType: "json",
});

return data;
} catch (e) {
throw (e instanceof AxiosError) ?
convertAxiosError(e) :
e;
}
};

/**
* Downloads (bypassing any caching) a file as a Uint8Array.
*
Expand Down Expand Up @@ -57,5 +82,7 @@ const getUint8ArrayFrom = async (fileUrl: string)
}
};


export {getUint8ArrayFrom};
export {
getJsonObjectFrom,
getUint8ArrayFrom,
};