Discover how using Axios wrapper functions can streamline your API calls, making integration effortless. This utility function handles various request types, authentication tokens, and data formats, enhancing the efficiency of your development process
🚀 Unlock the power of Axios wrapper functions to streamline API calls! This versatile utility handles different request types and authentication, making integration a breeze. Say goodbye to complex setups and hello to efficient development! 💻✨
1// ***** start - import from packages *****2import axios, { AxiosRequestConfig } from 'axios'3import Cookies from 'js-cookie'4import { ACCESS_TOKEN_KEY } from 'src/constants/constant'56// ***** end - import from packages *****78type requestType = 'get' | 'post' | 'delete' | 'postFormData' | 'postWithoutToken' | 'postFormDataWithoutToken'910// ***** start - Api function for call any type of apis *****11export const api = async (endpoint: string, data: any, type: requestType, configs?: AxiosRequestConfig<any>) => {12let res: any13const token = Cookies.get(ACCESS_TOKEN_KEY)1415switch (type) {16case 'get':17res = await axios({18data,19method: 'get',20headers: {21'Content-Type': 'application/json',22Authorization: `Bearer ${token}`23},24url: endpoint,25...configs26})27break28case 'post':29res = await axios({30data,31method: 'post',32headers: {33'Content-Type': 'application/json',34Authorization: `Bearer ${token}`35},36url: endpoint,37...configs38})39break40case 'delete':41res = await axios({42data,43method: 'delete',44headers: {45'Content-Type': 'application/json',46Authorization: `Bearer ${token}`47},48url: endpoint,49...configs50})51break52case 'postWithoutToken':53res = await axios({54method: 'post',55data,56headers: {57'Content-Type': 'application/json'58},59url: endpoint,60...configs61})62break63case 'postFormData':64res = await axios({65data,66method: 'post',67headers: {68'Content-Type': 'multipart/form-data',69Authorization: `Bearer ${token}`70},71url: endpoint,72...configs73})74break75case 'postFormDataWithoutToken':76res = await axios({77data,78method: 'post',79headers: {80'Content-Type': 'multipart/form-data'81},82url: endpoint,83...configs84})85break86default:87return true88}8990return res91}9293// ***** end - Api function for call any type of apis *****
Join the newsletter
Subscribe for weekly updates. No spams ever!
Copyright © 2024 | Hardik Desai | All Rights Reserved