2024-04-19 20:39:30 +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) => {
|
2024-04-18 09:16:41 +01:00
|
|
|
try {
|
|
|
|
const response = await fetch(url, {
|
|
|
|
headers: {
|
|
|
|
"User-Agent": "McUtils-JS-Library/1.0",
|
|
|
|
},
|
|
|
|
});
|
2024-04-15 08:56:26 +01:00
|
|
|
|
2024-04-18 09:18:32 +01:00
|
|
|
// 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;
|
|
|
|
}
|
|
|
|
|
2024-04-18 09:16:41 +01:00
|
|
|
const data = await response.json();
|
2024-04-15 08:56:26 +01:00
|
|
|
|
2024-04-18 09:16:41 +01:00
|
|
|
// Reject if the status code is not 200
|
|
|
|
if (!response.ok) {
|
|
|
|
reject(data as McUtilsAPIError);
|
|
|
|
return;
|
|
|
|
}
|
2024-04-15 08:56:26 +01:00
|
|
|
|
2024-04-18 09:16:41 +01:00
|
|
|
// 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;
|
|
|
|
}
|
2024-04-15 08:56:26 +01:00
|
|
|
|
2024-04-18 09:16:41 +01:00
|
|
|
// Resolve with the data
|
|
|
|
resolve(data as T);
|
|
|
|
} catch (error) {
|
|
|
|
reject(error);
|
|
|
|
}
|
2024-04-14 21:11:46 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|