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

78 lines
2 KiB
JavaScript
Raw Normal View History

2021-12-26 19:43:48 -05:00
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
"use strict";
(function() {
let moto = self.moto = self.moto || {};
2021-12-26 19:43:48 -05:00
2021-12-26 22:00:31 -05:00
if (moto.worker) return;
gapp.register('moto.worker');
2021-12-26 22:00:31 -05:00
let endpoints = {};
2021-12-26 19:43:48 -05:00
// code is running in the worker / server context
2021-12-26 22:00:31 -05:00
const dispatch = moto.worker = {
2021-12-27 18:13:11 -05:00
bind: (name, fn) => {
2021-12-26 22:00:31 -05:00
endpoints[name] = fn;
2021-12-27 18:13:11 -05:00
dispatch.send({bind: name});
2021-12-26 22:00:31 -05:00
},
2021-12-26 19:43:48 -05:00
send: (msg) => {
self.postMessage(msg);
},
onmessage: (e) => {
let msg = e.data,
2021-12-26 22:00:31 -05:00
run = endpoints[msg.task],
done = false,
2021-12-26 19:43:48 -05:00
send = {
data: (data, direct) => {
if (canSend(data)) {
dispatch.send({ done: false, data: data }, direct);
}
},
done: (data, direct) => {
if (canSend(data)) {
dispatch.send({ done: true, data: data }, direct);
done = true;
}
2021-12-26 19:43:48 -05:00
},
error: (data) => {
if (canSend(data)) {
done = true;
dispatch.send({ error: data });
}
}
},
canSend = (data) => {
if (done) {
console.log("unexpected reply dropped", {data, msg});
2021-12-26 19:43:48 -05:00
}
return !done;
2021-12-26 19:43:48 -05:00
};
if (run) {
try {
let data = run(msg.data, send);
if (data) {
send.done(data);
}
} catch (error) {
console.trace(error.stack);
dispatch.send({ data: {error: error.toString()}, done: true });
2021-12-26 19:43:48 -05:00
}
} else {
console.log({worker_unhandled: e});
send.error(`no registered endpoint: ${msg.task}`);
2021-12-26 19:43:48 -05:00
}
}
};
// attach onmessage hanler
self.onmessage = dispatch.onmessage;
})();