refactor: HttpGetJson

This commit is contained in:
手瓜一十雪 2024-05-13 17:53:50 +08:00
parent 317c6d96e3
commit 42ba524e4e

View File

@ -18,4 +18,31 @@ export class RequestUtil {
return result;
}
}
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: Record<string, string> = {}):
Promise<T> {
let body: BodyInit | undefined = undefined;
let requestInit: RequestInit = { method: method };
if (method.toUpperCase() === 'POST' && data !== undefined) {
body = JSON.stringify(data);
if (headers) {
headers['Content-Type'] = 'application/json';
requestInit.headers = new Headers(headers);
} else {
requestInit.headers = new Headers({ 'Content-Type': 'application/json' });
}
} else {
requestInit.headers = new Headers(headers);
}
try {
const response = await fetch(url, { ...requestInit, body });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const jsonResult = await response.json();
return jsonResult as T;
} catch (error: any) {
throw new Error(`Failed to fetch JSON: ${error.message}`);
}
}
}