2024-04-15 08:56:26 +01:00
|
|
|
import axios from "axios";
|
2024-04-16 23:32:06 +01:00
|
|
|
import { McUtilsAPIError } from "../types/error";
|
2024-04-14 21:11:46 +01:00
|
|
|
|
|
|
|
export default class WebRequest {
|
|
|
|
/**
|
|
|
|
* Gets a response from the given URL.
|
|
|
|
*
|
|
|
|
* @param url the url
|
|
|
|
* @returns the response
|
|
|
|
*/
|
2024-04-15 08:56:26 +01:00
|
|
|
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",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const data = response.data;
|
|
|
|
|
|
|
|
// Reject if the status code is not 200
|
|
|
|
if (response.status !== 200) {
|
2024-04-16 23:32:06 +01:00
|
|
|
reject(data as McUtilsAPIError);
|
2024-04-15 08:56:26 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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);
|
2024-04-14 21:11:46 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|