This repository has been archived by the owner on May 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
89 lines (72 loc) · 1.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const debug = require('debug')('aws-api-read-stream')
const { Readable, finished } = require('stream')
const STOPPED = 'stopped'
const READING = 'reading'
const DONE = 'done'
class AWSApiReadStream extends Readable {
constructor(fn, opts, nextToken) {
super({ ...opts, objectMode: true })
this._fn = fn
this._nextToken = nextToken
this._state = STOPPED
}
_read(size) {
if (this._state === READING) return
debug('_read', size, 'nextToken', this._nextToken)
this._execApiCall()
}
async _execApiCall() {
this._state = READING
try {
const res = await this._fn(this._nextToken)
if (!res) {
this._apiExecutionDone()
return
}
if (this._isInBufferMode()) {
this._buffer.push(res)
}
this._nextToken = res.NextToken || res.NextContinuationToken
if (!this._nextToken) {
this._apiExecutionDone()
return
}
if (!this.push(res)) {
this._state = STOPPED
return
}
this._execApiCall()
} catch (e) {
this.destroy(e)
}
}
_apiExecutionDone() {
this._state = DONE
this._nextToken = undefined
this.push(null)
}
stop() {
this._stop = true
this.destroy()
}
static from(fn, { nextToken, options } = {}) {
return new AWSApiReadStream(fn, options, nextToken)
}
// can probably come up with a better name...
// also, not sure if I should also use this.push in _read
// while in this mode...
readAll() {
this._buffer = []
return new Promise((res, rej) => {
this.resume()
finished(this, err => {
if (err) return rej(err)
res(this._buffer)
})
})
}
_isInBufferMode() {
return Array.isArray(this._buffer)
}
}
module.exports = AWSApiReadStream