Skip to content

Instantly share code, notes, and snippets.

@hkbertoson
Created May 31, 2023 15:22
Show Gist options
  • Save hkbertoson/a9ca7c1f9be0937dcc63222da066ac07 to your computer and use it in GitHub Desktop.
Save hkbertoson/a9ca7c1f9be0937dcc63222da066ac07 to your computer and use it in GitHub Desktop.
Utility class for making API requests.
/**
* Utility class for making API requests.
*/
export default class ApiRequest {
static async sendRequest(method: string, action: object): Promise<any> {
const url = '/backend/web/api/v4/react/endpoint';
const response = await fetch(`${url}?method=${method}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(action),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || `HTTP Error ${response.status}`);
}
return await response.json();
}
static async exportRequest(
method: string,
action: object
): Promise<Response> {
const url = '/backend/web/api/v4/react/endpoint';
const response = await fetch(`${url}?method=${method}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(action),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || `HTTP Error ${response.status}`);
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment