Javascript-Library/src/common/WebRequest.ts
2024-04-16 23:32:06 +01:00

39 lines
987 B
TypeScript

import axios from "axios";
import { McUtilsAPIError } from "../types/error";
export default class WebRequest {
/**
* Gets a response from the given URL.
*
* @param url the url
* @returns the response
*/
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) {
reject(data as McUtilsAPIError);
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);
});
}
}