Last active
September 17, 2018 13:29
-
-
Save diegomengarda/6653afe102f758c16002d481f648d2fe to your computer and use it in GitHub Desktop.
This file contains hidden or 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 axios from 'axios' | |
import interceptors from './interceptors' | |
import baseConfig from '../config' | |
/** | |
* Cria instância do axios para as requisições ajax | |
*/ | |
export const http = axios.create({ | |
baseURL: baseConfig.fullAPIPath, | |
headers: {'content-type': 'application/json'} | |
}) | |
/** | |
* Método auxiliar para setar o token no header do axios | |
*/ | |
export function setToken (token) { | |
http.defaults.headers.common.Authorization = `Bearer ${token}` | |
} | |
// receive store and data by options | |
export default function install (Vue, {router}) { | |
interceptors(http, router) | |
Object.defineProperty(Vue.prototype, '$http', { | |
get () { | |
return http | |
} | |
}) | |
} |
This file contains hidden or 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' | |
/** | |
* Interceptador de requisições com erro | |
*/ | |
export default (http, router) => { | |
// https://github.com/mzabriskie/axios#interceptors | |
http.interceptors.response.use( | |
response => response, | |
/** | |
* This is a central point to handle all | |
* error messages generated by HTTP | |
* requests | |
*/ | |
(error) => { | |
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, 403].indexOf(response.status) > -1) { | |
console.log('autenticação') | |
router.push({ name: 'auth' }) | |
} | |
/** | |
* Error messages are sent in arrays | |
*/ | |
if (isArray(response.data)) { | |
console.log(response.data) | |
/** | |
* Laravel generated validation errors are | |
* sent in an object | |
*/ | |
} else { | |
console.log(response.data) | |
} | |
return Promise.reject(error) | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment