Javascript-Library/src/common/WebRequest.ts
Liam db98cf20a1
All checks were successful
Publish Package / build (push) Successful in 19s
fix cache import
2024-04-19 20:39:30 +01:00

49 lines
1.3 KiB
TypeScript

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) => {
try {
const response = await fetch(url, {
headers: {
"User-Agent": "McUtils-JS-Library/1.0",
},
});
// 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;
}
const data = await response.json();
// 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);
}
});
}
}