github.com/lauslim12/expert-systems@v0.0.0-20221115131159-018513aad29c/web/src/utils/request.ts (about) 1 /** 2 * Handles errors from Fetch API. 3 * 4 * @param response - Fetch response object. 5 * @returns The result of the request, or an error if applicable 6 */ 7 const handleErrors = async (response: Response) => { 8 if (!response.ok) { 9 const error = await response.json(); 10 11 throw Error(error.message); 12 } 13 14 return await response.json(); 15 }; 16 17 /** 18 * Customized Fetch API to have better error handling. 19 * 20 * @param url - URL of the request 21 * @param requestBody - Body of the request 22 * @param requestMethod - Method of the request 23 * @returns Results of the request, or an error if applicable 24 */ 25 const request = async ( 26 url: string, 27 requestBody: any, 28 requestMethod: 'GET' | 'POST' 29 ) => { 30 const options: RequestInit = { 31 method: requestMethod, 32 headers: { 33 'Content-Type': 'application/json', 34 }, 35 body: JSON.stringify(requestBody), 36 }; 37 38 return await fetch(url, options).then(handleErrors); 39 }; 40 41 export default request;