import { isArray } from 'lodash' import { decode, encode } from 'querystring' const DEBUG = true const DEBUG_SESSION = 10942 export default (http, store, router) => { // Add a request interceptor http.interceptors.request.use((config) => { // PhpStorm needs to be started first, and a debug session // initiated there. The DEBUG_SESSION value able will also // need to be updated to match the session identifier. if (DEBUG) { let components = config.url.split('?') let qs = {} if (components[1]) { qs = decode(components[1]) } qs.XDEBUG_SESSION_START = DEBUG_SESSION config.url = `${components[0]}?${encode(qs)}` } return config }, (error) => { // Do something with request error return Promise.reject(error) }) // https://github.com/mzabriskie/axios#interceptors // Add a response interceptor http.interceptors.response.use((response) => { return response }, (error) => { /** * This is a central point to handle all * error messages generated by HTTP * requests */ const { response } = error /** * If token is either expired, not provided or invalid * then redirect to login. On server side the error * messages can be changed on app/Providers/EventServiceProvider.php */ if ([401, 400].indexOf(response.status) > -1) { router.push({ name: 'login.index' }) } /** * Error messages are sent in arrays */ if (isArray(response.data)) { store.dispatch('setMessage', { type: 'error', message: response.data.messages }) /** * Laravel generated validation errors are * sent in an object */ } else { store.dispatch('setMessage', { type: 'validation', message: response.data }) } store.dispatch('setFetching', { fetching: false }) return Promise.reject(error) }) }