Skip to content
This repository has been archived by the owner on Feb 13, 2024. It is now read-only.

flush: guarantee that all inflight messages are sent #352

Merged
merged 5 commits into from
Nov 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class Analytics {
this.flushInterval = options.flushInterval || 10000
this.flushed = false
this.errorHandler = options.errorHandler
this.pendingFlush = null
Object.defineProperty(this, 'enable', {
configurable: false,
writable: false,
Expand Down Expand Up @@ -236,7 +237,7 @@ class Analytics {
* @return {Analytics}
*/

flush (callback) {
async flush (callback) {
callback = callback || noop

if (!this.enable) {
Expand All @@ -254,6 +255,13 @@ class Analytics {
return Promise.resolve()
}

try {
if (this.pendingFlush) { await this.pendingFlush }
} catch (err) {
this.pendingFlush = null
throw err
}

const items = this.queue.splice(0, this.flushAt)
const callbacks = items.map(item => item.callback)
const messages = items.map(item => item.message)
Expand Down Expand Up @@ -291,7 +299,8 @@ class Analytics {
req.timeout = typeof this.timeout === 'string' ? ms(this.timeout) : this.timeout
}

return this.axiosInstance.post(`${this.host}${this.path}`, data, req)
return (this.pendingFlush = this.axiosInstance
.post(`${this.host}${this.path}`, data, req)
.then(() => {
done()
return Promise.resolve(data)
Expand All @@ -310,7 +319,7 @@ class Analytics {

done(err)
throw err
})
}))
}

_isErrorRetryable (error) {
Expand Down