|
|
|
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';
|
|
|
|
export const API_STATUS = '/api/v1/auth/status';
|
|
|
|
export const API_INIT = '/api/v1/auth/init';
|
|
|
|
export const API_LOGIN = '/api/v1/auth/login';
|
|
|
|
import * as DataEvent from '../com/events/DataEvent';
|
|
|
|
export default class APIUtils {
|
|
|
|
//--------------------------
|
|
|
|
// constructor
|
|
|
|
//--------------------------
|
|
|
|
constructor() {}
|
|
|
|
//--------------------------
|
|
|
|
// public
|
|
|
|
//--------------------------
|
|
|
|
login(data) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this._request(
|
|
|
|
API_LOGIN,
|
|
|
|
DataEvent.AUTH_STATUS,
|
|
|
|
REQUEST_TYPE_POST,
|
|
|
|
CONTENT_TYPE_JSON,
|
|
|
|
data
|
|
|
|
)
|
|
|
|
.then(result => {
|
|
|
|
resolve(result);
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
reject(err);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
init(data) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this._request(API_INIT, DataEvent.API_INIT, REQUEST_TYPE_POST, CONTENT_TYPE_JSON, data)
|
|
|
|
.then(result => {
|
|
|
|
resolve(result);
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
reject(err);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
//--------------------------
|
|
|
|
// private
|
|
|
|
//--------------------------
|
|
|
|
_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) {
|
|
|
|
let response = JSON.parse(request['response']);
|
|
|
|
resolve(response);
|
|
|
|
} else {
|
|
|
|
let error = JSON.parse(request['response']);
|
|
|
|
reject(error);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if (requestType == REQUEST_TYPE_PUT || requestType == REQUEST_TYPE_POST) {
|
|
|
|
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);
|
|
|
|
//pass element to display request progress
|
|
|
|
}
|
|
|
|
}
|