-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
alexeykosinski
committed
Jul 2, 2021
1 parent
7bd5713
commit 11978f4
Showing
2 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
const MAX_QUERY_PER_SECOND = 4; | ||
|
||
class ApiQueueService { | ||
constructor() { | ||
this.queue = []; | ||
this.executeHistory = []; | ||
this.isRun = false; | ||
} | ||
|
||
executeInQueue(method, ...data) { | ||
return new Promise((resolve, reject) => { | ||
this.addToQueue(method, data, ({ err, data }) => { | ||
if (err) { | ||
return reject(err); | ||
} | ||
return resolve(data); | ||
}); | ||
}); | ||
} | ||
|
||
addToQueue(method, data, cb) { | ||
this.queue.push({ method, data, cb }); | ||
this.run(); | ||
} | ||
|
||
run(force = false) { | ||
if (this.isRun && !force) { | ||
return; | ||
} | ||
this.isRun = true; | ||
if (this.isBusy()) { | ||
const timer = setTimeout(() => { | ||
clearTimeout(timer); | ||
this.run(true); | ||
}, 100); | ||
return; | ||
} | ||
const q = this.getFirst(); | ||
if (!q) { | ||
this.isRun = false; | ||
return; | ||
} | ||
this.execute(q).finally(() => { | ||
this.removeFirst(); | ||
if (this.queue.length === 0) { | ||
this.isRun = false; | ||
return; | ||
} | ||
this.run(true); | ||
}); | ||
} | ||
|
||
getFirst() { | ||
return this.queue && this.queue[0]; | ||
} | ||
|
||
removeFirst() { | ||
this.queue.splice(0, 1); | ||
} | ||
|
||
isBusy() { | ||
return this.getCountQueryInLastSecond() >= MAX_QUERY_PER_SECOND; | ||
} | ||
|
||
getCountQueryInLastSecond() { | ||
const currentTime = +new Date(); | ||
this.executeHistory = this.executeHistory.filter((d) => d.time > (currentTime - 1000)); | ||
return this.executeHistory.length; | ||
} | ||
|
||
execute(q) { | ||
this.executeHistory.push({ time: +new Date() }); | ||
return q.method(...(q.data || [])).then((data) => { | ||
q.cb({ data }); | ||
}).catch((err) => { | ||
q.cb({ err }); | ||
}); | ||
|
||
} | ||
} | ||
|
||
module.exports = new ApiQueueService(); |