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

81 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 { data } = root;
const { local } = data;
2020-04-07 21:45:21 -04:00
const KEY = "moto-ajax";
const MOID = moto.id = local.getItem(KEY) || (Date.now().toString(36)+rnd()+rnd());
local.setItem(KEY, MOID);
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"] = MOID;
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 restore(id) {
MOID = moto.id = id;
local.setItem(KEY, MOID);
}
exports({
new(cb, rt) { return new Ajax(cb, rt) },
call,
restore,
});
2017-04-18 17:09:33 -04:00
});