Created
December 12, 2016 10:42
-
-
Save 58bits/c7b7dccf3f922fde13275d1a54990838 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment