Skip to content

Commit

Permalink
update: add emprtyQueue option while starting queue
Browse files Browse the repository at this point in the history
  • Loading branch information
hemant-fundwave committed Apr 4, 2024
1 parent 363a682 commit 1e29732
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,13 @@ export class FetchQueue {

/**
* Enables the queuing of fetch requests in the FetchQueue.
* @param {boolean} [emptyQueue] If true, empties the queue before starting.
* @returns {void}
*/
public startQueue(): void {
public startQueue(emptyQueue?: boolean): void {
if (emptyQueue) this.#queue = [];
if (this.#debug && emptyQueue) this.#urlsQueued = [];

this.#pauseQueue = false;
this.#emitRequestCompletedEvent();
}
Expand Down Expand Up @@ -180,17 +184,16 @@ export class FetchQueue {

if (this.#activeRequests < this.#concurrent && !this.#pauseQueue) {
return task();
} else {
return new Promise((resolve, reject) => {
const queueTask = () => {
task().then(resolve).catch(reject);
};
this.#queue.push(queueTask);
if (this.#debug) {
this.#urlsQueued.push(url.toString().split("/").slice(-3).join("/"));
}
});
}
return new Promise((resolve, reject) => {
const queueTask = () => {
task().then(resolve).catch(reject);
};
this.#queue.push(queueTask);
if (this.#debug) {
this.#urlsQueued.push(url.toString().split("/").slice(-3).join("/"));
}
});
};
})();
}
37 changes: 37 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,41 @@ describe("test case with start and pause queue", () => {

expect(fetchQueue.getQueueLength()).toBe(0);
});

// it("start fetchQueue with emptyQueue set to true", async () => {
// const fetchQueue = new FetchQueue({ concurrent: 1 });
// const fetch = fetchQueue.getFetchMethod();

// const mockFetch = jest.fn().mockImplementation(async (url, urlIndex) => {
// switch (urlIndex) {
// case 0:
// expect(fetchQueue.getActiveRequests()).toBe(0);
// expect(fetchQueue.getQueueLength()).toBe(0);
// fetchQueue.pauseQueue();
// break;
// case 1:
// expect(fetchQueue.getQueueLength()).toBe(1);
// expect(fetchQueue.getActiveRequests()).toBe(0);
// break;
// case 2:
// expect(fetchQueue.getQueueLength()).toBe(2);
// expect(fetchQueue.getActiveRequests()).toBe(0);
// fetchQueue.startQueue(true);
// break;
// case 3:
// expect(fetchQueue.getQueueLength()).toBe(0);
// expect(fetchQueue.getActiveRequests()).toBe(1);
// break;
// }

// await fetch(url);
// jest.advanceTimersByTime(5000);
// return;
// });

// const promises = urls.map((url, urlIndex) => mockFetch(url, urlIndex));
// await Promise.all(promises);

// expect(fetchQueue.getQueueLength()).toBe(0);
// });
});

0 comments on commit 1e29732

Please sign in to comment.