easy api setup with axios with svelte

علی ذوالفقار
1401/09/05 18:18:35 (37)
create a base url for production mode : 
var baseURL = 'https://api.akomsn.cf/v1/' ; 

if run script from localhost use dev api 
if(window.location.hostname=='localhost') baseURL = 'http://localhost:82/v1/' ; 

create axios api 
const axiosAPI = axios.create({
    baseURL: baseURL
});


// implement a method to execute all the request from here.
const apiRequest = (method, url, request , token) => {
    const headers = {
        authorization: "" ,
        authtoken : token
    };
    //using the axios instance to perform the request that received from each http method
    return axiosAPI({
            method,
            url,
            data: request,
            headers
        }).then(res => {
            return Promise.resolve(res.data);
        })
        .catch(err => {
            return Promise.reject(err);
        });
};

// function to execute the http get request
const get = (url, request , token) => apiRequest("get", url, request, token);

// function to execute the http delete request
const deleteRequest = (url, request , token) => apiRequest("delete", url, request, token);

// function to execute the http post request
const post = (url, request, token) => apiRequest("post", url, request, token);

// function to execute the http put request
const put = (url, request, token) => apiRequest("put", url, request, token);

// function to execute the http path request
const patch = (url, request, token) => apiRequest("patch", url, request, token);

// call api and get current member
const refreshMember = async(token)=>{
    try {
        let res = await get("/whoami",{},token);
        if(res.isLogin){
            member.set(res); // member is a svelte store 
            localStorage.setItem('member',JSON.stringify(res)); 
        }else{
            replace('/login')
        }
    } catch (error) {
        console.log('refresh member error : ' , error);
        member.set({isLogin : false});
    }
}

// expose your method to other services or actions
const API = {
    get,
    delete: deleteRequest,
    post,
    put,
    patch , 
    refreshMember
};

export default API;

Back