aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/chunked-requester.ts
blob: f7b1464a701d898cdb3dab469f0206313448355c (plain)
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
72
73
74
75
76
import axios from "axios";

interface ChunkedRequest {
    url: string,
    parameters: object,
    resolve(value: unknown): unknown,
    reject(): unknown,
}

export default class ChunkedRequester
{
    #requests: ChunkedRequest[] = [];

    readonly #delay: number;
    readonly #limit: number;
    #timeout: ReturnType<typeof setTimeout>|undefined = undefined;

    constructor(limit: number = 16, delay: number = 500) {
        if (limit < 1) {
            throw new Error('Limit must be positive');
        }

        this.#limit = limit;
        this.#delay = delay;
    }

    addRequest(url: string, parameters: object = {}): Promise<unknown>
    {
        return new Promise((resolve, reject) => {
            this.#requests.push({
                url,
                parameters,
                resolve,
                reject
            });
            this.#startRequests();
        });
    }

    #startRequests(): void
    {
        if (this.#requests.length === 0) {
            return;
        }

        if (this.#requests.length < this.#limit) {
            this.clearTimeout();
        }

        if (this.#timeout !== undefined) {
            return;
        }

        this.#timeout = setTimeout(
            () => {
                Promise.all(
                    this.#requests
                        .splice(0, this.#limit)
                        .map(({url, parameters, resolve, reject}) => {
                            return axios.get(url, {params: parameters}).then(resolve, reject);
                        })
                ).then(() => {
                    this.clearTimeout();
                    this.#startRequests();
                });
            }
            , this.#delay
        );
    }

    clearTimeout(): void
    {
        clearTimeout(this.#timeout);
        this.#timeout = undefined;
    }
}