forked from heroku-examples/node-workers-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
71 lines (60 loc) · 1.71 KB
/
client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Store for all of the jobs in progress
let jobs = {};
// Kick off a new job by POST-ing to the server
async function addJob() {
let res = await fetch('job/', {method: 'POST'});
let job = await res.json();
jobs[job.id] = {id: job.id, state: "queued"};
render();
}
// Fetch updates for each job
async function updateJobs() {
for (let id of Object.keys(jobs)) {
let res = await fetch(`/job/${id}`);
let result = await res.json();
if (!!jobs[id]) {
jobs[id] = result;
}
render();
}
}
// Delete all stored jobs
function clear() {
jobs = {};
render();
}
// Update the UI
function render() {
let s = "";
for (let id of Object.keys(jobs)) {
s += renderJob(jobs[id]);
}
// For demo simplicity this blows away all of the existing HTML and replaces it,
// which is very inefficient. In a production app a library like React or Vue should
// handle this work
document.querySelector("#job-summary").innerHTML = s;
}
// Renders the HTML for each job object
function renderJob(job) {
let progress = job.progress || 0;
let color = "bg-light-purple";
if (job.state === "completed") {
color = "bg-purple";
progress = 100;
} else if (job.state === "failed") {
color = "bg-dark-red";
progress = 100;
}
return document.querySelector('#job-template')
.innerHTML
.replace('{{id}}', job.id)
.replace('{{state}}', job.state)
.replace('{{color}}', color)
.replace('{{progress}}', progress);
}
// Attach click handlers and kick off background processes
window.onload = function() {
document.querySelector("#add-job").addEventListener("click", addJob);
document.querySelector("#clear").addEventListener("click", clear);
setInterval(updateJobs, 200);
};