Advertisement
Badal_hs_shah

Untitled

Feb 10th, 2023
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import qs from 'qs';
  2. import axios, {AxiosResponse} from 'axios';
  3. import {t} from 'i18next';
  4. import {Alert} from 'react-native';
  5. const CONTENT_TYPE_URL_ENCODED =
  6.   'application/x-www-form-urlencoded;charset=UTF-8';
  7. const defaultConfig = {
  8.   // timeout: 30000, //100000,
  9.   headers: {
  10.     'content-type': CONTENT_TYPE_URL_ENCODED,
  11.   },
  12.   validateStatus: function (status) {
  13.     return status < 600;
  14.   },
  15. };
  16.  
  17. const instance = axios.create(defaultConfig);
  18.  
  19. // Sends a GET request to the specified URL with the specified options
  20. // async function get(url: string, params: any, {signal}) {
  21. //   return sendRequest('get', url, params, {signal});
  22. // }
  23. async function get(url: string, params: any) {
  24.   return sendRequest('get', url, params);
  25. }
  26.  
  27. // Sends a POST request to the specified URL with the specified params and options
  28. async function post(url: any, params: any, options: any = {}) {
  29.   // Set the default value for the options.headers object
  30.   options.headers = options.headers || {};
  31.   console.log('Header is ===================>', options);
  32.   // Set the content-type header to the specified value, or the default value if not specified
  33.   options.headers['content-type'] =
  34.     options.headers['content-type'] || CONTENT_TYPE_URL_ENCODED;
  35.   return sendRequest('post', url, params, {...options});
  36. }
  37.  
  38. // Sends a PATCH request to the specified URL with the specified params
  39. async function patch(url: any, params: any) {
  40.   return sendRequest('patch', url, params);
  41. }
  42.  
  43. // Sends a PUT request to the specified URL with the specified params
  44. async function put(url: any, params: any) {
  45.   sendRequest('put', url, params);
  46. }
  47.  
  48. // Sends a DELETE request to the specified URL
  49. async function Delete(url: any) {
  50.   return sendRequest('delete', url);
  51. }
  52.  
  53. // Sends a request to the specified URL using the specified method and options
  54. async function sendRequest(
  55.   method: string,
  56.   url: any,
  57.   params: any = {},
  58.   options: any = {},
  59. ) {
  60.   // Create a cancel token and a timer to cancel the request if it takes too long
  61.   const source = axios.CancelToken.source();
  62.   // const timer = setTimeout(() => {
  63.   //   source.cancel();
  64.   // }, 60 * 1000);
  65.   // Set the cancel token as an option for the request
  66.   options.cancelToken = source.token;
  67.   // Send the request using the specified method, URL, params, and options
  68.  
  69.   const response = await instance[method](url, params, options);
  70.   // Clear the timer
  71.   //clearTimeout(timer);
  72.   // Return the response
  73.  
  74.   console.log('response umang is', response);
  75.   return response;
  76. }
  77.  
  78. export function errorInterceptor(): string | void {
  79.   instance.interceptors.response.use(undefined, error => {
  80.     const {response} = error;
  81.  
  82.     if (!response) {
  83.       // network error
  84.       console.error(error);
  85.       return;
  86.     }
  87.  
  88.     if ([401, 403].includes(response.status)) {
  89.       // auto logout if 401 or 403 response returned from api
  90.       // accountService.logout();
  91.     }
  92.  
  93.     // const errorMessage = response.data;
  94.     // console.log('errorMessage', errorMessage)
  95.     return response;
  96.   });
  97. }
  98.  
  99. /**
  100.  * @param {object} data json object that contains key value for request to server
  101.  * This will take data as JSON Object and return in Form of json Object and encode the url
  102.  * @returns {object} This function will return object that hold url encoded data
  103.  */
  104. export const getFormDataObjForUrlEn = data => {
  105.   const formData = Object.keys(data)
  106.     .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
  107.     .join('&');
  108.   return formData;
  109. };
  110.  
  111. const methodMap = {
  112.   GET: get,
  113.   POST: post,
  114.   PATCH: patch,
  115.   PUT: put,
  116.   DELETE: Delete,
  117. };
  118.  
  119. export async function send(params: {
  120.   method: string;
  121.   url: string;
  122.   obj?: any;
  123.   isRawData?: boolean;
  124.   contentType?: any;
  125.   signal?: any;
  126. }): Promise<any> {
  127.   // Validate the input params
  128.   validateParams(params);
  129.  
  130.   // Get the appropriate function for the specified HTTP method
  131.   const func = getMethodFunc(params.method);
  132.  
  133.   // Send the request and handle the response/error
  134.   return request(func, params);
  135. }
  136.  
  137. function validateParams(params: any) {
  138.   if (!params || typeof params !== 'object') {
  139.     throw new Error('params is undefined or not an object');
  140.   }
  141. }
  142.  
  143. function getMethodFunc(method: string) {
  144.   const func = methodMap[method];
  145.   if (!func) {
  146.     throw new Error(`Invalid HTTP method: ${method}`);
  147.   }
  148.   return func;
  149. }
  150.  
  151. async function request(func: any, params: any) {
  152.   console.log('request =============>', params.contentType);
  153.   try {
  154.     let result;
  155.     if (params.method === 'GET') {
  156.       let obj = params.obj;
  157.       console.log('obj param is', params);
  158.       if (!params.isRawData) {
  159.         // obj = qs.stringify(obj);
  160.         // console.log('obj is', obj);
  161.  
  162.         result = await func(params.url, obj, {signal: params.signal});
  163.         console.log('bbbbb', result);
  164.       } else {
  165.         result = await func(params.url, {signal: params.signal});
  166.       }
  167.     } else {
  168.       let obj = params.obj;
  169.       if (params.method === 'POST' && !params.isRawData) {
  170.         obj = qs.stringify(obj);
  171.       }
  172.       const options = {
  173.         headers: {
  174.           'content-type': params.contentType || '',
  175.         },
  176.       };
  177.       result = await func(params.url, obj, options);
  178.     }
  179.     return result;
  180.   } catch (error) {
  181.     console.log('uuu error is', error);
  182.     //const err = errorInterceptor();
  183.     throw error;
  184.   }
  185. }
  186.  
  187. export enum RW3ResponseError {
  188.   RW3Success = 0,
  189.   RW3Error409 = 1,
  190.   RW3Error401 = 2,
  191.   RW3ErrorResponseMessage = 3,
  192. }
  193.  
  194. export function getResponseStatus(response: any): RW3ResponseError {
  195.   if ([200].includes(response.status)) {
  196.     return RW3ResponseError.RW3Success;
  197.   } else {
  198.     if (response.status === 409) {
  199.       return RW3ResponseError.RW3Error409;
  200.     } else if (response.status === 401) {
  201.       Alert.alert(
  202.         `${t('INVALID_CREDENTIAL_TITLE')}`,
  203.         response.data.LoginErrorMessage,
  204.         [{text: `${t('ALERT_DISMISS')}`, style: 'cancel'}],
  205.       );
  206.       return RW3ResponseError.RW3Error401;
  207.     } else {
  208.       if ('LoginErrorMessage' in response.data) {
  209.         Alert.alert('', response.data.LoginErrorMessage, [
  210.           {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
  211.         ]);
  212.       } else {
  213.         Alert.alert('', response.data.Message, [
  214.           {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
  215.         ]);
  216.       }
  217.       return RW3ResponseError.RW3ErrorResponseMessage;
  218.     }
  219.   }
  220. }
  221.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement