koel/resources/assets/js/services/http.js

73 lines
2 KiB
JavaScript
Raw Normal View History

2016-12-20 15:44:47 +00:00
import axios from 'axios'
2016-11-26 03:25:35 +00:00
import NProgress from 'nprogress'
2016-11-26 03:25:35 +00:00
import { event } from '../utils'
import { ls } from '../services'
2016-02-09 04:57:08 +00:00
2015-12-13 04:42:28 +00:00
/**
* Responsible for all HTTP requests.
*/
2016-06-25 10:15:57 +00:00
export const http = {
2016-11-26 03:25:35 +00:00
request (method, url, data, successCb = null, errorCb = null) {
2016-12-20 15:44:47 +00:00
axios.request({
url,
data,
2016-12-20 15:44:47 +00:00
method: method.toLowerCase()
}).then(successCb).catch(errorCb)
2016-06-25 16:05:24 +00:00
},
2015-12-13 04:42:28 +00:00
2016-11-26 03:25:35 +00:00
get (url, successCb = null, errorCb = null) {
return this.request('get', url, {}, successCb, errorCb)
2016-06-25 16:05:24 +00:00
},
2015-12-29 01:35:22 +00:00
2016-11-26 03:25:35 +00:00
post (url, data, successCb = null, errorCb = null) {
return this.request('post', url, data, successCb, errorCb)
2016-06-25 16:05:24 +00:00
},
2015-12-13 04:42:28 +00:00
2016-11-26 03:25:35 +00:00
put (url, data, successCb = null, errorCb = null) {
return this.request('put', url, data, successCb, errorCb)
2016-06-25 16:05:24 +00:00
},
2015-12-13 04:42:28 +00:00
2016-11-26 03:25:35 +00:00
delete (url, data = {}, successCb = null, errorCb = null) {
return this.request('delete', url, data, successCb, errorCb)
2016-06-25 16:05:24 +00:00
},
2015-12-13 04:42:28 +00:00
/**
* Init the service.
*/
2016-11-26 03:25:35 +00:00
init () {
2016-12-20 15:44:47 +00:00
axios.defaults.baseURL = '/api'
2016-12-20 15:44:47 +00:00
// Intercept the request to make sure the token is injected into the header.
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${ls.get('jwt-token')}`
return config
})
2016-12-20 15:44:47 +00:00
// Intercept the response and…
axios.interceptors.response.use(response => {
NProgress.done()
// …get the token from the header or response data if exists, and save it.
const token = response.headers['Authorization'] || response.data['token']
if (token) {
2016-11-26 03:25:35 +00:00
ls.set('jwt-token', token)
}
2016-12-20 15:44:47 +00:00
return response
}, error => {
NProgress.done()
// Also, if we receive a Bad Request / Unauthorized error
if (error.response.status === 400 || error.response.status === 401) {
// and we're not trying to login
if (!(error.config.method === 'post' && /\/api\/me\/?$/.test(error.config.url))) {
// the token must have expired. Log out.
event.emit('logout')
}
}
2016-12-20 15:44:47 +00:00
return Promise.reject(error)
2016-11-26 03:25:35 +00:00
})
}
}