• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1const Minipass = require('minipass')
2const _flush = Symbol('_flush')
3const _flushed = Symbol('_flushed')
4const _flushing = Symbol('_flushing')
5class Flush extends Minipass {
6  constructor (opt = {}) {
7    if (typeof opt === 'function')
8      opt = { flush: opt }
9
10    super(opt)
11
12    // or extend this class and provide a 'flush' method in your subclass
13    if (typeof opt.flush !== 'function' && typeof this.flush !== 'function')
14      throw new TypeError('must provide flush function in options')
15
16    this[_flush] = opt.flush || this.flush
17  }
18
19  emit (ev, ...data) {
20    if ((ev !== 'end' && ev !== 'finish') || this[_flushed])
21      return super.emit(ev, ...data)
22
23    if (this[_flushing])
24      return
25
26    this[_flushing] = true
27
28    const afterFlush = er => {
29      this[_flushed] = true
30      er ? super.emit('error', er) : super.emit('end')
31    }
32
33    const ret = this[_flush](afterFlush)
34    if (ret && ret.then)
35      ret.then(() => afterFlush(), er => afterFlush(er))
36  }
37}
38
39module.exports = Flush
40