Advertisement
Badal_hs_shah

API

Jan 16th, 2023
68
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 checkResponse from './CheckResponse';
  4.  
  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, {signal}) {
  21.   return sendRequest('get', url, {signal});
  22. }
  23.  
  24. // Sends a POST request to the specified URL with the specified params and options
  25. async function post(url: any, params: any, options: any = {}) {
  26.   // Set the default value for the options.headers object
  27.   options.headers = options.headers || {};
  28.   console.log('Header is ===================>', options);
  29.   // Set the content-type header to the specified value, or the default value if not specified
  30.   options.headers['content-type'] =
  31.     options.headers['content-type'] || CONTENT_TYPE_URL_ENCODED;
  32.   return sendRequest('post', url, params, {...options});
  33. }
  34.  
  35. // Sends a PATCH request to the specified URL with the specified params
  36. async function patch(url: any, params: any) {
  37.   return sendRequest('patch', url, params);
  38. }
  39.  
  40. // Sends a PUT request to the specified URL with the specified params
  41. async function put(url: any, params: any) {
  42.   sendRequest('put', url, params);
  43. }
  44.  
  45. // Sends a DELETE request to the specified URL
  46. async function Delete(url: any) {
  47.   return sendRequest('delete', url);
  48. }
  49.  
  50. // Sends a request to the specified URL using the specified method and options
  51. async function sendRequest(
  52.   method: string,
  53.   url: any,
  54.   params: any = {},
  55.   options: any = {},
  56. ) {
  57.   // Create a cancel token and a timer to cancel the request if it takes too long
  58.   const source = axios.CancelToken.source();
  59.   const timer = setTimeout(() => {
  60.     source.cancel();
  61.   }, 60 * 1000);
  62.   // Set the cancel token as an option for the request
  63.   options.cancelToken = source.token;
  64.   // Send the request using the specified method, URL, params, and options
  65.   console.log('===============>', options);
  66.  
  67.   const response = await instance[method](url, params, options);
  68.   // Clear the timer
  69.   clearTimeout(timer);
  70.   // Return the response
  71.   return response;
  72. }
  73.  
  74. export function errorInterceptor(): string | void {
  75.   instance.interceptors.response.use(undefined, error => {
  76.     const {response} = error;
  77.  
  78.     if (!response) {
  79.       // network error
  80.       console.error(error);
  81.       return;
  82.     }
  83.  
  84.     if ([401, 403].includes(response.status)) {
  85.       // auto logout if 401 or 403 response returned from api
  86.       // accountService.logout();
  87.     }
  88.  
  89.     // const errorMessage = response.data;
  90.     // console.log('errorMessage', errorMessage)
  91.     return response;
  92.   });
  93. }
  94.  
  95. /**
  96.  * @param {object} data json object that contains key value for request to server
  97.  * This will take data as JSON Object and return in Form of json Object and encode the url
  98.  * @returns {object} This function will return object that hold url encoded data
  99.  */
  100. export const getFormDataObjForUrlEn = data => {
  101.   const formData = Object.keys(data)
  102.     .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
  103.     .join('&');
  104.   return formData;
  105. };
  106.  
  107. const methodMap = {
  108.   GET: get,
  109.   POST: post,
  110.   PATCH: patch,
  111.   PUT: put,
  112.   DELETE: Delete,
  113. };
  114.  
  115. export async function send(params: {
  116.   method: string;
  117.   url: string;
  118.   obj?: any;
  119.   isRawData?: boolean;
  120.   contentType?: any;
  121.   signal?: any;
  122. }): Promise<any> {
  123.   // Validate the input params
  124.   validateParams(params);
  125.  
  126.   // Get the appropriate function for the specified HTTP method
  127.   const func = getMethodFunc(params.method);
  128.  
  129.   // Send the request and handle the response/error
  130.   let result = await request(func, params);
  131.  
  132.   // checkResponse({
  133.   //   res: result,
  134.   //   successCodes: [200, 201],
  135.   // });
  136.   //if (result.status === 200 || result.status === 201) {
  137.   return result;
  138.   //}
  139. }
  140.  
  141. function validateParams(params: any) {
  142.   if (!params || typeof params !== 'object') {
  143.     throw new Error('params is undefined or not an object');
  144.   }
  145. }
  146.  
  147. function getMethodFunc(method: string) {
  148.   const func = methodMap[method];
  149.   if (!func) {
  150.     throw new Error(`Invalid HTTP method: ${method}`);
  151.   }
  152.   return func;
  153. }
  154.  
  155. async function request(func: any, params: any) {
  156.   console.log('request =============>', params.contentType);
  157.   try {
  158.     let result;
  159.     if (params.method === 'GET') {
  160.       result = await func(params.url, {signal: params.signal});
  161.     } else {
  162.       let obj = params.obj;
  163.       if (params.method === 'POST' && !params.isRawData) {
  164.         obj = qs.stringify(obj);
  165.       }
  166.       const options = {
  167.         headers: {
  168.           'content-type': params.contentType || '',
  169.         },
  170.       };
  171.       result = await func(params.url, obj, options);
  172.     }
  173.     console.log('------', result);
  174.     return result;
  175.   } catch (error) {
  176.     //const err = errorInterceptor();
  177.     throw error;
  178.   }
  179. }
  180.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement