UNPKG

khatavani-client

Version:

The Backend-Api-Integration package simplifies interaction with the backend API by providing a set of CRUD methods for common endpoints. It abstracts away the complexity of making HTTP requests and handling responses, allowing developers to focus on appli

135 lines (106 loc) 3.46 kB
import { anyKeyAndValue } from "./CollectionTypes"; import { cloneResponse, mergeErrorMessages } from "./helper"; /** * @public * @return {responseJson} it return promise * @remark that method is responsible for sending the request to the backend */ export async function fetchHelper( endpoint: string, method: string, accessToken: string | null = null, khID: string | null = null, body: anyKeyAndValue | null = null, options: anyKeyAndValue | null = null, SERVER_URL: string | undefined ): Promise<any> { try { var url = SERVER_URL + endpoint; if (options) { const queryParams = new URLSearchParams(options); url = url + `?${queryParams.toString()}`; } var requestObject: anyKeyAndValue = { method: method, headers: { 'Content-Type': 'application/json', } } if (accessToken) { requestObject.headers.Authorization = 'Bearer ' + accessToken; } if (khID) { requestObject.headers.khID = khID; } if (body) { requestObject.body = JSON.stringify(body); } var response: anyKeyAndValue; var responseJson: anyKeyAndValue; var responseMessage: string; try { response = await fetch(url, requestObject); responseJson = await cloneResponse(response) if (response.ok) { return responseJson } else { responseMessage = mergeErrorMessages(responseJson) } var errorMessage = "Server error:" + response.status + " Message: " + responseMessage; return Promise.reject(errorMessage); } catch (e: any) { return Promise.reject(e.message); } } catch (e: any) { return Promise.reject(e.message); } } /** * @public * @return {responseJson} it return promise * @remark that method is responsible for sending the request with the file to the backend */ export async function UploadFile( method: string, body: any, headers: anyKeyAndValue, SERVER_URL: string ): Promise<any> { try { const url = SERVER_URL; const requestObject: anyKeyAndValue = { method: method, headers: headers, }; if (body) { requestObject.body = body; } var response: anyKeyAndValue; var responseJson: anyKeyAndValue; var responseMessage: string; try { response = await fetch(url, requestObject); responseJson = await cloneResponse(response) if (response.ok) { return responseJson } else { responseMessage = mergeErrorMessages(responseJson) } var errorMessage = "Server error:" + response.status + " Message: " + responseMessage; return Promise.reject(errorMessage); } catch (e: any) { return Promise.reject(e.message); } } catch (e: any) { return Promise.reject(e.message); } }