migrate to fetch
Some checks failed
Publish Package / build (push) Has been cancelled

This commit is contained in:
Lee
2024-04-18 09:16:41 +01:00
parent cbb534adf4
commit bdc56e454a
3 changed files with 24 additions and 86 deletions

View File

@ -1,4 +1,3 @@
import axios from "axios";
import { McUtilsAPIError } from "../types/error";
export default class WebRequest {
@ -10,29 +9,33 @@ export default class WebRequest {
*/
public static get<T>(url: string): Promise<T> {
return new Promise(async (resolve, reject) => {
const response = await axios.get(url, {
validateStatus: () => true, // Don't throw errors
headers: {
"User-Agent": "McUtils-JS-Library/1.0",
},
});
try {
const response = await fetch(url, {
headers: {
"User-Agent": "McUtils-JS-Library/1.0",
},
});
const data = response.data;
const data = await response.json();
// Reject if the status code is not 200
if (response.status !== 200) {
reject(data as McUtilsAPIError);
return;
// Reject if the status code is not 200
if (!response.ok) {
reject(data as McUtilsAPIError);
return;
}
// Resolve with a buffer if the content type is an image
if (response.headers.get("content-type")?.includes("image/")) {
const arrayBuffer = await response.arrayBuffer();
resolve(Buffer.from(arrayBuffer) as unknown as T);
return;
}
// Resolve with the data
resolve(data as T);
} catch (error) {
reject(error);
}
// Resolve with a buffer if the content type is an image
if (response.headers["content-type"].includes("image/")) {
resolve(Buffer.from(data, "utf-8") as unknown as T);
return;
}
// Resolve with the data
resolve(data as T);
});
}
}