UNPKG

1.11 kBJavaScriptView Raw
1'use strict'
2
3const MinipassPipeline = require('minipass-pipeline')
4
5class CachingMinipassPipeline extends MinipassPipeline {
6 #events = []
7 #data = new Map()
8
9 constructor (opts, ...streams) {
10 // CRITICAL: do NOT pass the streams to the call to super(), this will start
11 // the flow of data and potentially cause the events we need to catch to emit
12 // before we've finished our own setup. instead we call super() with no args,
13 // finish our setup, and then push the streams into ourselves to start the
14 // data flow
15 super()
16 this.#events = opts.events
17
18 /* istanbul ignore next - coverage disabled because this is pointless to test here */
19 if (streams.length) {
20 this.push(...streams)
21 }
22 }
23
24 on (event, handler) {
25 if (this.#events.includes(event) && this.#data.has(event)) {
26 return handler(...this.#data.get(event))
27 }
28
29 return super.on(event, handler)
30 }
31
32 emit (event, ...data) {
33 if (this.#events.includes(event)) {
34 this.#data.set(event, data)
35 }
36
37 return super.emit(event, ...data)
38 }
39}
40
41module.exports = CachingMinipassPipeline