svg-layout-designer-react/public/workers/message_worker.js
2022-09-16 10:03:41 +00:00

63 lines
1.7 KiB
JavaScript

const DELAY_BEFORE_SEND = 200;
const queue = [];
let messagePacket = [];
onmessage = async(e) => {
let packetLength
const url = e.data.url;
const state = e.data.state;
const request = {
ApplicationState: state
};
const dataParsed = JSON.stringify(request, GetCircularReplacerKeepDataStructure());
queue.push(request);
fetch(url, {
method: 'POST',
headers: new Headers({
// eslint-disable-next-line @typescript-eslint/naming-convention
'Content-Type': 'application/json'
}),
body: dataParsed
})
.then((response) =>
response.json()
)
.then(async(json) => {
messagePacket.push.apply(messagePacket, json.messages);
queue.pop();
// The sleep allow the message packet to be filled by
// others requests before being sent as a single batch
// Reducing the wait time will reduce latency but increase error rate
let doLoop = true;
do {
packetLength = messagePacket.length;
await sleep(DELAY_BEFORE_SEND);
const newPacketLength = messagePacket.length;
doLoop = newPacketLength !== packetLength;
packetLength = newPacketLength;
} while (doLoop);
if (queue.length <= 0 && messagePacket.length > 0) {
console.debug(`[GetFeedback] Packet size before sent: ${messagePacket.length}`)
postMessage(messagePacket)
messagePacket.splice(0);
}
});
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function GetCircularReplacerKeepDataStructure()
{
return (key, value) => {
if (key === 'parent') {
return;
}
return value;
};
}