import 'whatwg-fetch' ; import localStorage from './../localStorage' ; import parseError , { ApiError } from './parseError' ; const api = { get ( url ) { return api . fetchJson ( url ) ; } , post ( url , data ) { return api . fetchJson ( url , { body : JSON . stringify ( data ) , method : 'POST' , } ) ; } , delete ( url , data ) { return api . fetchJson ( url , { body : JSON . stringify ( data ) , method : 'DELETE' , } ) ; } , put ( url , data ) { return api . fetchJson ( url , { body : JSON . stringify ( data ) , method : 'PUT' , } ) ; } , fetchJson ( url , params ) { return new Promise ( ( resolve , reject ) => { this . fetch ( url , params ) . then ( response => { if ( response . ok ) { return response . json ( ) . then ( json => resolve ( json ) ) . catch ( err => reject ( new ApiError ( err . message , response ) ) ) ; } else { return response . json ( ) . then ( json => reject ( new ApiError ( parseError ( json ) , response ) ) ) . catch ( ( ) => { reject ( new ApiError ( `${ response . status } - ${ response . url }` , response ) ) ; } ) ; } } ) . catch ( err => { reject ( err ) ; } ) ; } ) ; } , fetch ( url , params = { } ) { url = window . location . origin + url ; const options = { ... requestOptions , ... params , } ; options . headers = { ... options . headers , ... getAuthHeaders ( ) , } ; return fetch ( url , options ) ; } , } ; const requestOptions = { credentials : 'same-origin' , headers : { Accept : 'application/json' , 'Content-Type' : 'application/json; charset=utf-8' , } , mode : 'same-origin' , cache : 'no-store' , } ; export function getAuthHeaders ( ) { const accessToken = getAccessToken ( ) ; const csrfToken = getXCSRFToken ( ) ; return { 'X-CSRF-Token' : csrfToken , Authorization : `Bearer ${ accessToken }` , } ; } export function getNoCacheHeaders ( ) { return { 'cache-control' : 'max-age=0' , expires : '0' , pragma : 'no-cache' , } ; } export const getXCSRFToken = ( ) => { const metaTag = document . querySelector ( '[name=grv_csrf_token]' ) ; return metaTag ? metaTag . content : '' ; } ; export function getAccessToken ( ) { const bearerToken = localStorage . getBearerToken ( ) || { } ; return bearerToken . accessToken ; } export function getHostName ( ) { return location . hostname + ( location . port ? ':' + location . port : '' ) ; } export default api ;