2019-12-02 22:07:16 +01:00
|
|
|
export const REQUEST_TYPE_POST = 'POST';
|
|
|
|
export const REQUEST_TYPE_GET = 'GET';
|
|
|
|
export const REQUEST_TYPE_PUT = 'PUT';
|
|
|
|
export const REQUEST_TYPE_DELETE = 'DELETE';
|
|
|
|
export const CONTENT_TYPE_JSON = 'json';
|
|
|
|
export const CONTENT_TYPE_FORM = 'x-www-form-urlencoded';
|
|
|
|
import * as DataEvent from '../events/DataEvent';
|
|
|
|
export default class APIUtils {
|
|
|
|
//--------------------------
|
|
|
|
// constructor
|
|
|
|
//--------------------------
|
|
|
|
constructor() {
|
|
|
|
this.percentComplete = 0;
|
|
|
|
this.token = null;
|
|
|
|
}
|
|
|
|
//--------------------------
|
|
|
|
// methods
|
|
|
|
//--------------------------
|
|
|
|
authStatus() {
|
|
|
|
this.request('/api/v1/auth/status').then(r => {
|
|
|
|
let response = JSON.parse(r.request['response']);
|
|
|
|
if (response.type === DataEvent.API_REQUEST_GOOD) {
|
|
|
|
this.token = response.token;
|
|
|
|
} else {
|
|
|
|
//don't set token
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
request(
|
|
|
|
requestURL,
|
|
|
|
eventType,
|
|
|
|
requestType = REQUEST_TYPE_GET,
|
|
|
|
contentType = CONTENT_TYPE_JSON,
|
|
|
|
requestData = null
|
|
|
|
) {
|
|
|
|
var self = this;
|
2020-05-05 22:44:45 +02:00
|
|
|
return new Promise(function (resolve, reject) {
|
2019-12-02 22:07:16 +01:00
|
|
|
var request = new XMLHttpRequest();
|
|
|
|
request.upload.onprogress = self.handleLoadProgress;
|
|
|
|
request.open(requestType, requestURL, true);
|
|
|
|
request.onload = () => {
|
|
|
|
if (request.status == 200) {
|
|
|
|
resolve({
|
|
|
|
request,
|
|
|
|
eventType
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
reject({
|
|
|
|
request,
|
|
|
|
eventType
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if (requestType == REQUEST_TYPE_PUT || requestType == REQUEST_TYPE_POST) {
|
2019-12-03 02:59:04 +01:00
|
|
|
if (
|
|
|
|
eventType === DataEvent.API_PAGE_WRITE ||
|
|
|
|
eventType === DataEvent.API_IMAGES_UPLOAD ||
|
2020-03-01 06:01:34 +01:00
|
|
|
eventType === DataEvent.API_SETTINGS_WRITE ||
|
2020-05-05 22:44:45 +02:00
|
|
|
eventType === DataEvent.API_PAGE_DELETE ||
|
|
|
|
eventType === DataEvent.API_RENDER_PAGES
|
2019-12-03 02:59:04 +01:00
|
|
|
)
|
|
|
|
request.setRequestHeader('x-access-token', self.token);
|
2020-05-23 21:40:01 +02:00
|
|
|
|
2019-12-02 22:07:16 +01:00
|
|
|
switch (contentType) {
|
|
|
|
case CONTENT_TYPE_JSON:
|
|
|
|
request.setRequestHeader('Content-type', 'application/' + contentType);
|
|
|
|
request.send(JSON.stringify(requestData));
|
|
|
|
break;
|
|
|
|
case CONTENT_TYPE_FORM:
|
|
|
|
request.send(requestData);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
request.send();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
//--------------------------
|
|
|
|
// event handlers
|
|
|
|
//--------------------------
|
|
|
|
handleLoadProgress(e) {
|
|
|
|
this.percentComplete = Math.ceil((e.loaded / e.total) * 100);
|
|
|
|
//this.emitEvent(DataEvent.UPLOAD_PROGRESS);
|
|
|
|
}
|
|
|
|
}
|