File size: 1,215 Bytes
2d460b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const getBasePath = () => {
  return document.location.origin + document.location.pathname;
};

const generateDetails = async () => {
  const details = await fetch(`${getBasePath()}/details`);
  return await details.json();
};

const createTask = async (prompt) => {
  const taskResponse = await fetch(`${getBasePath()}task/create?prompt=${prompt}`);
  const task = await taskResponse.json();

  return task;
};

const queueTask = async (task_id) => {
  const queueResponse = await fetch(`${getBasePath()}task/queue?task_id=${task_id}`);
  return queueResponse.json();
};

const pollTask = async (task) => {
  const taskResponse = await fetch(`${getBasePath()}task/poll?task_id=${task.task_id}`);

  return await taskResponse.json();
};

const longPollTask = async (task, interval = 10_000, max) => {
  const etaDisplay = document.querySelector('.eta');

  task = await pollTask(task);

  if (task.status === 'completed' || (max && task.poll_count > max)) {
    return task;
  }

  etaDisplay.textContent = Math.round(task.eta);

  await new Promise((resolve) => setTimeout(resolve, interval));

  return await longPollTask(task, interval, max);
};

export { generateDetails, createTask, queueTask, longPollTask };