Files
react-training/hotel-management/src/helpers/sendRequest.ts
T
2023-11-08 17:46:26 +07:00

38 lines
834 B
TypeScript

// Constants
import { BASE_URL } from '@constant/path';
// Types
import { IResponse } from '@type/responses';
type TMethodRequest = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
/**
* The send request method to the server
* @param path The path of URL
* @param body The content will push on
* @param method HTTP method
* @returns The status code and message from server
*/
export const sendRequest = async <T>(
path: string,
method: TMethodRequest = 'GET',
body?: BodyInit
): Promise<IResponse<T>> => {
const response = await fetch(BASE_URL + path, {
method,
body,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
const data = (await response.json()) as T;
return {
statusCode: response.status,
msg: response.statusText,
data,
};
};