This commit is contained in:
@ -1,4 +1,5 @@
|
||||
import axios, { AxiosResponse } from "axios";
|
||||
import axios from "axios";
|
||||
import { Error } from "../types/error";
|
||||
|
||||
export default class WebRequest {
|
||||
/**
|
||||
@ -7,12 +8,31 @@ export default class WebRequest {
|
||||
* @param url the url
|
||||
* @returns the response
|
||||
*/
|
||||
public static get(url: string): Promise<AxiosResponse<any, any>> {
|
||||
return axios.get(url, {
|
||||
validateStatus: () => true, // Don't throw errors
|
||||
headers: {
|
||||
"User-Agent": "McUtils-JS-Library/1.0",
|
||||
},
|
||||
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 Error);
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user