import { getAuthHeader, getCsrfToken } from "./auth.service"; import config from '../config' import store from '../store' import axios from 'axios' const apiUrl = config.apiUrl const initialHeader = { 'Content-Type': 'application/json' } export const APIService = async(url, method, body, headers = initialHeader) => { return await APIAuthService(url, method, body, headers) } /** * Fetch with Authorization token, and csrf token * @param {*} url * @param {*} method * @param {*} body * @param {*} headers */ export const APIAuthService = async(url, method = 'post', body, headers = initialHeader) => { return new Promise((resolve, reject) => { try { // Remove start foward slash if(url.length && url.charAt(0) === '/') { url = url.substr(1) } console.log('APIAuthService', { url, method, headers, body, isFormData: body instanceof FormData ? 'yes' : 'no' }) // Add CSRF token headers = {...headers, 'x-csrf-token': getCsrfToken(), ...getAuthHeader()} const options = { headers, method } axios.post(`${apiUrl}/`+url, body, options).then(response => { resolve(handleResponse(response, url)) }).catch(err => { console.log('APIAuthService Error (1)', err, {url, method}) store.dispatch(AlertErrorAction(err.message)) }) } catch (err) { console.log('APIAuthService Error (2)', err, {url, method}) reject(err) } }) }