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; return new Promise(function(resolve, reject) { 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) { if ( eventType === DataEvent.API_PAGE_WRITE || eventType === DataEvent.API_IMAGES_UPLOAD || eventType === DataEvent.API_SETTINGS_WRITE ) request.setRequestHeader('x-access-token', self.token); 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); } }