grid-apps-cmms/src/moto/ajax.js

80 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-06-03 22:39:30 -04:00
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
2017-04-18 22:22:29 -04:00
2017-04-18 17:09:33 -04:00
"use strict";
gapp.register("moto.ajax", [], (root, exports) => {
2017-04-18 17:09:33 -04:00
function rnd() {
return Math.round(Math.random()*0xffffffff).toString(36);
}
const KV = data.local,
KEY = "moto-ajax",
TIME = Date.now,
MOKEY = moto.id = KV.getItem(KEY) || (TIME().toString(36)+rnd()+rnd());
2020-04-07 21:45:21 -04:00
KV.setItem(KEY, MOKEY);
2020-04-07 21:45:21 -04:00
const STATES = [
"request not initialized", // 0
"server connection established", // 1
"request recieved", // 2
"processing request", // 3
"request complete" // 4
];
2017-04-18 17:09:33 -04:00
class Ajax {
constructor(callback, responseType) {
2017-04-18 17:09:33 -04:00
this.ajax = new XMLHttpRequest();
this.ajax.onreadystatechange = this.onStateChange.bind(this);
this.ajax.withCredentials = true;
this.state = STATES[0];
this.callback = callback;
this.responseType = responseType;
}
onStateChange() {
2017-04-18 17:09:33 -04:00
this.state = STATES[this.ajax.readyState];
if (this.ajax.readyState === 4 && this.callback) {
2020-04-07 21:45:21 -04:00
let status = this.ajax.status;
2017-04-18 17:09:33 -04:00
if (status >= 200 && status < 300) {
this.callback(this.ajax.responseType ? this.ajax.response : this.ajax.responseText, this.ajax);
} else {
this.callback(null, this.ajax);
}
}
}
2017-04-18 17:09:33 -04:00
request(url, send, headers) {
2017-04-18 17:09:33 -04:00
this.ajax.open(send ? "POST" : "GET", url, true);
if (this.responseType) this.ajax.responseType = this.responseType;
headers = headers || {};
headers["X-Moto-Ajax"] = MOKEY;
2020-04-07 21:45:21 -04:00
for (let k in headers) {
2017-04-18 17:09:33 -04:00
this.ajax.setRequestHeader(k, headers[k]);
}
if (send) {
this.ajax.send(send);
} else {
this.ajax.send();
}
return this;
}
}
function call(url, handler) {
return new Ajax(handler).request(url);
}
function callAjax(url, handler) {
return new Ajax(handler).request(url);
};
function restore(id) {
MOKEY = moto.id = id;
KV.setItem(KEY, MOKEY);
}
exports({ Ajax, call, callAjax, restore });
2017-04-18 17:09:33 -04:00
});