2016-02-09 04:57:08 +00:00
|
|
|
import Vue from 'vue';
|
2016-07-09 04:06:14 +00:00
|
|
|
import $ from 'jquery';
|
|
|
|
import NProgress from 'nprogress';
|
|
|
|
|
|
|
|
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-06-25 16:05:24 +00:00
|
|
|
request(method, url, data, successCb = null, errorCb = null) {
|
2016-07-09 04:06:14 +00:00
|
|
|
return $.ajax({
|
|
|
|
data,
|
|
|
|
dataType: 'json',
|
|
|
|
url: `/api/${url}`,
|
|
|
|
method: method.toUpperCase(),
|
|
|
|
headers: {
|
|
|
|
Authorization: `Bearer ${ls.get('jwt-token')}`,
|
|
|
|
}
|
|
|
|
}).done(successCb).fail(errorCb);
|
2016-06-25 16:05:24 +00:00
|
|
|
},
|
2015-12-13 04:42:28 +00:00
|
|
|
|
2016-06-25 16:05:24 +00:00
|
|
|
get(url, successCb = null, errorCb = null) {
|
|
|
|
return this.request('get', url, {}, successCb, errorCb);
|
|
|
|
},
|
2015-12-29 01:35:22 +00:00
|
|
|
|
2016-06-25 16:05:24 +00:00
|
|
|
post(url, data, successCb = null, errorCb = null) {
|
|
|
|
return this.request('post', url, data, successCb, errorCb);
|
|
|
|
},
|
2015-12-13 04:42:28 +00:00
|
|
|
|
2016-06-25 16:05:24 +00:00
|
|
|
put(url, data, successCb = null, errorCb = null) {
|
|
|
|
return this.request('put', url, data, successCb, errorCb);
|
|
|
|
},
|
2015-12-13 04:42:28 +00:00
|
|
|
|
2016-06-25 16:05:24 +00:00
|
|
|
delete(url, data = {}, successCb = null, errorCb = null) {
|
|
|
|
return this.request('delete', url, data, successCb, errorCb);
|
|
|
|
},
|
2015-12-13 04:42:28 +00:00
|
|
|
|
2016-07-09 04:06:14 +00:00
|
|
|
/**
|
|
|
|
* Init the service.
|
|
|
|
*/
|
|
|
|
init() {
|
|
|
|
$(document).ajaxComplete((e, r, settings) => {
|
|
|
|
NProgress.done();
|
|
|
|
|
|
|
|
if (r.status === 400 || r.status === 401) {
|
2016-07-09 05:20:27 +00:00
|
|
|
if (!(settings.method === 'POST' && /\/api\/me\/?$/.test(settings.url))) {
|
2016-07-09 04:06:14 +00:00
|
|
|
// This is not a failed login. Log out then.
|
|
|
|
event.emit('logout');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const token = r.getResponseHeader('Authorization');
|
|
|
|
if (token) {
|
|
|
|
ls.set('jwt-token', token);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (r.responseJSON && r.responseJSON.token && r.responseJSON.token.length > 10) {
|
|
|
|
ls.set('jwt-token', r.responseJSON.token);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
},
|
2015-12-13 04:42:28 +00:00
|
|
|
};
|