szurubooru/public_html/js/Api.js

61 lines
1.1 KiB
JavaScript
Raw Normal View History

2014-08-31 23:22:56 +02:00
var App = App || {};
2014-09-08 22:02:28 +02:00
App.API = function(jQuery, promise, appState) {
2014-08-31 23:22:56 +02:00
var baseUrl = '/api/';
function get(url, data) {
return request('GET', url, data);
2014-09-08 22:02:28 +02:00
}
2014-08-31 23:22:56 +02:00
function post(url, data) {
return request('POST', url, data);
2014-09-08 22:02:28 +02:00
}
2014-08-31 23:22:56 +02:00
function put(url, data) {
return request('PUT', url, data);
2014-09-08 22:02:28 +02:00
}
2014-08-31 23:22:56 +02:00
function _delete(url, data) {
return request('DELETE', url, data);
2014-09-08 22:02:28 +02:00
}
2014-08-31 23:22:56 +02:00
function request(method, url, data) {
var fullUrl = baseUrl + '/' + url;
fullUrl = fullUrl.replace(/\/{2,}/, '/');
2014-09-04 18:06:25 +02:00
return promise.make(function(resolve, reject) {
2014-09-08 22:02:28 +02:00
jQuery.ajax({
2014-09-04 19:21:18 +02:00
headers: {
'X-Authorization-Token': appState.get('loginToken') || '',
},
2014-08-31 23:22:56 +02:00
success: function(data, textStatus, xhr) {
resolve({
status: xhr.status,
json: data});
},
error: function(xhr, textStatus, errorThrown) {
reject({
status: xhr.status,
2014-09-08 22:02:28 +02:00
json: xhr.responseJSON ?
xhr.responseJSON :
{error: errorThrown}});
2014-08-31 23:22:56 +02:00
},
type: method,
url: fullUrl,
data: data,
});
});
2014-09-08 22:02:28 +02:00
}
2014-08-31 23:22:56 +02:00
return {
get: get,
post: post,
put: put,
delete: _delete
};
};
App.DI.registerSingleton('api', App.API);