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
361 lines (356 loc) • 11.3 kB
JavaScript
function mergeErrorMessages(responseJson) {
let errorMessages = undefined;
if (responseJson?.details) {
errorMessages = responseJson.details;
}
else if (responseJson) {
errorMessages = [responseJson];
}
let mergedMessage = undefined;
if (errorMessages) {
mergedMessage = errorMessages.map((item) => item.message).join(', ');
}
return mergedMessage ? mergedMessage : " Contact Admin !!!";
}
const cloneResponse = async (res) => {
var temporaryValue = res.clone();
try {
return await res.json();
}
catch (e) {
return await temporaryValue.text();
// that is for "" string or null get crash at converting the
// it to the json
}
};
/**
* @public
* @return {responseJson} it return promise
* @remark that method is responsible for sending the request to the backend
*/
async function fetchHelper(endpoint, method, accessToken = null, khID = null, body = null, options = null, SERVER_URL) {
try {
var url = SERVER_URL + endpoint;
if (options) {
const queryParams = new URLSearchParams(options);
url = url + `?${queryParams.toString()}`;
}
var requestObject = {
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;
var responseJson;
var responseMessage;
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) {
return Promise.reject(e.message);
}
}
catch (e) {
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
*/
async function UploadFile(method, body, headers, SERVER_URL) {
try {
const url = SERVER_URL;
const requestObject = {
method: method,
headers: headers,
};
if (body) {
requestObject.body = body;
}
var response;
var responseJson;
var responseMessage;
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) {
return Promise.reject(e.message);
}
}
catch (e) {
return Promise.reject(e.message);
}
}
const POST_METHOD = "POST";
const GET_METHOD = "GET";
const PUT_METHOD = "PUT";
const PATCH_METHOD = "PATCH";
const DELETE_METHOD = "DELETE";
const FETCHING_ITEMS_LIMIT = 50;
const EMULATERPATH = "http://127.0.0.1:5001/khatavani-933a5/asia-south1/api/";
const SERVERPATH = "https://asia-south1-khatavani-933a5.cloudfunctions.net/api/";
const PRODUCTION_ENV = 'production';
/**
* @public
* @return {} it return the object which contain the options regarding the request
* which are going to send .
* @remark that method is responsible for getting the all possible options for the request
*/
const optionsCallBack = (options, pageParam) => {
return {
limit: FETCHING_ITEMS_LIMIT,
cursur: pageParam * FETCHING_ITEMS_LIMIT,
...options,
};
};
const checkEnv = () => {
var useEmulater = true;
// it necessary to Add the env with REACT_APP_ACTUAL_SERVER = true if you
// want to connect to the actual service in development
if (process.env.NODE_ENV === PRODUCTION_ENV || process?.env?.REACT_APP_ACTUAL_SERVER === "true") {
useEmulater = false;
}
return useEmulater ? EMULATERPATH : SERVERPATH;
};
class CRUDMethods {
constructor(endpoint) {
this.endpoint = endpoint;
this.serverUrl = checkEnv();
}
async create(accessToken, khID = null, body = null, options = null) {
return fetchHelper(this.endpoint, POST_METHOD, accessToken, khID, body, options, this.serverUrl);
}
async get(accessToken, khID = null, body = null, options = null, pageParam = 0) {
return fetchHelper(this.endpoint, GET_METHOD, accessToken, khID, body, optionsCallBack(options, pageParam), this.serverUrl);
}
async getAll(accessToken, khID = null, body = null, options = null) {
return fetchHelper(this.endpoint, GET_METHOD, accessToken, khID, body, options, this.serverUrl);
}
async getOne(accessToken, khID = null, id) {
return fetchHelper(`${this.endpoint}/${id}`, GET_METHOD, accessToken, khID, null, null, this.serverUrl);
}
async put(accessToken, khID = null, body = null, id, options = null) {
return fetchHelper(`${this.endpoint}/${id}`, PUT_METHOD, accessToken, khID, body, options, this.serverUrl);
}
async patch(accessToken, khID = null, body = null, id, options = null) {
return fetchHelper(`${this.endpoint}/${id}`, PATCH_METHOD, accessToken, khID, body, options, this.serverUrl);
}
async delete(accessToken, khID = null, id, options = null) {
return fetchHelper(`${this.endpoint}/${id}`, DELETE_METHOD, accessToken, khID, null, options, this.serverUrl);
}
}
const KHATAVANI_ENDPOINT = "khatavani";
const USER_ENDPOINT = "Users";
const RESOURCE_ENDPOINT = "resources";
const ACCOUNT_ENDPOINT = "accounts";
const VOUCHER_ENDPOINT = "vouchers";
const TRANSACTION_ENDPOINT = "transactions";
const RESOURCEGROUPS_ENDPOINT = "resourceGroups";
const USERROLE_ENDPOINT = "userlevels";
const BALANCE_ENDPOINT = "balances";
const FILE_ENDPOINT = "files";
const BATCH_ENDPOINT = "batches";
const SERIES_ENDPOINT = "serializedid";
const MESSAGE_ENDPOINT = "messages";
const WAID_ENDPOINT = "waid";
const PAYMENT_ENDPOINT = "receipts";
const MARKER_ENDPOINT = "markers";
const PACKAGE_ENDPOINT = "packages";
/**
*Returns Khatavani Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Khatavani = () => {
return new CRUDMethods(KHATAVANI_ENDPOINT);
};
/**
*Returns Users Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Users = () => {
return new CRUDMethods(USER_ENDPOINT);
};
/**
*Returns Resources Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Resources = () => {
return new CRUDMethods(RESOURCE_ENDPOINT);
};
/**
*Returns Accounts Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Accounts = () => {
return new CRUDMethods(ACCOUNT_ENDPOINT);
};
/**
*Returns Vouchers Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Vouchers = () => {
return new CRUDMethods(VOUCHER_ENDPOINT);
};
/**
*Returns Transactions Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Transactions = () => {
return new CRUDMethods(TRANSACTION_ENDPOINT);
};
/**
*Returns ResourceGroups Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const ResourceGroups = () => {
return new CRUDMethods(RESOURCEGROUPS_ENDPOINT);
};
/**
*Returns UserRoles Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const UserRoles = () => {
return new CRUDMethods(USERROLE_ENDPOINT);
};
/**
*Returns Balance Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Balance = () => {
return new CRUDMethods(BALANCE_ENDPOINT);
};
/**
*Returns Files Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Files = () => {
return new CRUDMethods(FILE_ENDPOINT);
};
/**
*Returns Batch Object which has the create ,get,getOne,getAll,put,patch,delete
*
* @return Object of the class CRUDMethods
*/
const Batch = () => {
return new CRUDMethods(BATCH_ENDPOINT);
};
/**
*Returns Serialized Number (autoIncrementId) which has the get
*
* @return Object of the class CRUDMethods
*/
const Serialized = () => {
return new CRUDMethods(SERIES_ENDPOINT);
};
/**
*Returns Messages from users which has the get
*
* @return Object of the class CRUDMethods
*/
const Messages = () => {
return new CRUDMethods(MESSAGE_ENDPOINT);
};
/**
*Returns WA_ID from service with timestamp
*
* @return Object of the class CRUDMethods
*/
const WAID = () => {
return new CRUDMethods(WAID_ENDPOINT);
};
/**
*Returns Payment from service with timestamp
*
* @return Object of the class CRUDMethods
*/
const PAYMENT = () => {
return new CRUDMethods(PAYMENT_ENDPOINT);
};
/**
*Returns Markers from service
*
* @return Object of the class CRUDMethods
*/
const Markers = () => {
return new CRUDMethods(MARKER_ENDPOINT);
};
/**
*Returns Markers from service
*
* @return Object of the class CRUDMethods
*/
const Packages = () => {
return new CRUDMethods(PACKAGE_ENDPOINT);
};
/**
* @public
* @return {allFiles} it is the promises array .
* @remark it Uploads the Particular file or image to the firebase bucket
*/
const UploadData = async (fileStore, authToken, khID, id, Public = false) => {
const allFiles = fileStore.map(async (element) => {
const uploadImageObject = { ...element.ImageMetaData };
if (Public) {
uploadImageObject.public = Public;
}
else {
uploadImageObject.accountID = id;
}
const fileEndpoint = Files();
const data = await fileEndpoint.create(authToken, khID, uploadImageObject);
let file = element.ImageData;
if (element.ImageData.data) {
file = element.ImageData.data;
}
return UploadFile(PUT_METHOD, file, data.headers, data.url);
});
await Promise.all(allFiles);
return allFiles;
};
export { Accounts, Balance, Batch, Files, Khatavani, Markers, Messages, PAYMENT, Packages, ResourceGroups, Resources, Serialized, Transactions, UploadData, UserRoles, Users, Vouchers, WAID };