Javascript-Library/src/common/WebRequest.ts
Liam bdc56e454a
Some checks failed
Publish Package / build (push) Has been cancelled
migrate to fetch
2024-04-18 09:16:41 +01:00

42 lines
1.0 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",
},
});
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);
}
});
}
}