-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (65 loc) · 1.32 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
import {EventEmitter} from 'node:events'
import {Readable} from 'node:stream'
import {fetchPosition} from './lib/fetch-position.js'
const livePositionsAsEventEmitter = (opt = {}) => {
const {
interval,
timeout,
} = {
interval: 3000, // 3s
timeout: 2500, // 2.5s
...opt,
}
const out = new EventEmitter()
const fetch = () => {
fetchPosition({timeout})
.then(data => out.emit('data', data))
.catch(err => out.emit('error', err))
timer = setTimeout(fetch, interval)
}
let timer = setTimeout(fetch, interval)
out.stop = () => {
if (timer === null) return;
clearTimeout(timer)
timer = null
}
return out
}
const livePositionsAsReadableStream = (opt = {}) => {
const {
interval,
timeout,
} = {
interval: 3000, // 3s
timeout: 2500, // 2.5s
...opt,
}
const fetch = async () => {
try {
const data = await fetchPosition({timeout})
out.push(data)
} catch (err) {
out.destroy(err)
return;
}
timer = setTimeout(fetch, interval)
}
let timer = setTimeout(fetch, interval)
const out = new Readable({
objectMode: true,
read: () => {},
destroy: (err, cb) => {
if (timer !== null) {
clearTimeout(timer)
timer = null
}
cb(err)
}
})
return out
}
export {
fetchPosition,
livePositionsAsEventEmitter as asEventEmitter,
livePositionsAsReadableStream as asStream,
}