Advertisement
benshepherd

Untitled

Apr 9th, 2019
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { getAuthHeader, getCsrfToken } from "./auth.service";
  2. import config from '../config'
  3. import store from '../store'
  4. import axios from 'axios'
  5.  
  6. const apiUrl = config.apiUrl
  7. const initialHeader = {
  8.     'Content-Type': 'application/json'
  9. }
  10.  
  11. export const APIService = async(url, method, body, headers = initialHeader) => {
  12.     return await APIAuthService(url, method, body, headers)
  13. }
  14.  
  15. /**
  16.  * Fetch with Authorization token, and csrf token
  17.  * @param {*} url
  18.  * @param {*} method
  19.  * @param {*} body
  20.  * @param {*} headers
  21.  */
  22. export const APIAuthService = async(url, method = 'post', body, headers = initialHeader) => {
  23.     return new Promise((resolve, reject) => {
  24.         try {
  25.             // Remove start foward slash
  26.             if(url.length && url.charAt(0) === '/') {
  27.                 url = url.substr(1)
  28.             }
  29.  
  30.             console.log('APIAuthService', {
  31.                 url, method, headers, body,
  32.                 isFormData: body instanceof FormData ? 'yes' : 'no'
  33.             })
  34.  
  35.             // Add CSRF token
  36.             headers = {...headers, 'x-csrf-token': getCsrfToken(), ...getAuthHeader()}
  37.    
  38.             const options = {
  39.                 headers,
  40.                 method
  41.             }
  42.            
  43.    
  44.             axios.post(`${apiUrl}/`+url, body, options).then(response => {
  45.                 resolve(handleResponse(response, url))
  46.             }).catch(err => {
  47.                 console.log('APIAuthService Error (1)', err, {url, method})
  48.                 store.dispatch(AlertErrorAction(err.message))
  49.             })
  50.         }
  51.         catch (err) {
  52.             console.log('APIAuthService Error (2)', err, {url, method})
  53.             reject(err)
  54.         }
  55.     })
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement