89 lines
2.3 KiB
JavaScript
89 lines
2.3 KiB
JavaScript
/**
|
|
* Web worker handling message API.
|
|
* When sending quickly multiple request,
|
|
* a single packet of message merging all request' responses is returned
|
|
*/
|
|
|
|
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;
|
|
}
|
|
|
|
if (key === 'containers') {
|
|
return [...value.entries()].map((keyPair) => {
|
|
return {
|
|
Key: keyPair[0],
|
|
Value: keyPair[1]
|
|
};
|
|
});
|
|
}
|
|
|
|
if (key === 'symbols') {
|
|
return [...value.entries()].map((keyPair) => {
|
|
return {
|
|
Key: keyPair[0],
|
|
Value: keyPair[1]
|
|
};
|
|
});
|
|
}
|
|
|
|
if (key === 'linkedContainers') {
|
|
return Array.from(value);
|
|
}
|
|
};
|
|
}
|
|
|