-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.js
86 lines (77 loc) · 2.09 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
const API_URL = 'http://localhost:3000'
let counter = 0
async function consumeAPI(signal) {
const response = await fetch(API_URL, {
signal
})
const reader = response.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(parseNDJSON())
// .pipeTo(new WritableStream({
// write(chunk) {
// console.log(++counter, 'chunk', chunk)
// }
// }))
return reader
}
function appendToHTML(element) {
return new WritableStream({
write({ title, description, url_anime}) {
const card = `
<article>
<div class="text">
<h3>[${++counter}] ${title}</h3>
<p>${description.slice(0, 100)}</p>
<a href="${url_anime}"> Here's why</a>
</div>
</article>
`
element.innerHTML += card
},
abort(reason) {
console.log('aborted**', reason)
}
})
}
// essa função vai se certificar que caso dois chunks cheguem em uma unica transmissao
// converta corretamente para JSON
// dado:{}\n{}
// deve
// {}
// {}
function parseNDJSON() {
let ndjsonBuffer = ''
return new TransformStream({
transform(chunk, controller) {
ndjsonBuffer += chunk
const items = ndjsonBuffer.split('\n')
items.slice(0, -1)
.forEach(item => controller.enqueue(JSON.parse(item)))
ndjsonBuffer = items[items.length -1]
},
flush(controller) {
if(!ndjsonBuffer) return;
controller.enqueue(JSON.parse(ndjsonBuffer))
}
})
}
const [
start,
stop,
cards
] = ['start', 'stop', 'cards'].map(item => document.getElementById(item))
let abortController = new AbortController()
start.addEventListener('click', async () => {
try {
const readable = await consumeAPI(abortController.signal)
// add signal and await to handle the abortError exception after abortion
await readable.pipeTo(appendToHTML(cards), { signal: abortController.signal })
} catch (error) {
if (!error.message.includes('abort')) throw error
}
})
stop.addEventListener('click', () => {
abortController.abort()
console.log('aborting...')
abortController = new AbortController()
})