Skip to content

Commit fcb4a04

Browse files
committedJan 11, 2023
refactoring
Signed-off-by: Erick Wendel <erick.workspace@gmail.com>
1 parent 0b8d10d commit fcb4a04

File tree

3 files changed

+64
-58
lines changed

3 files changed

+64
-58
lines changed
 

‎preclass/annotations.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
https://developer.chrome.com/articles/fetch-streaming-requests/
22
https://www.kaggle.com/datasets/danielalbarracinm/list-of-anime-from-1990-to-2022?resource=download
3-
https://www.tpeczek.com/2019/04/fetch-api-streams-api-ndjson-and-aspnet.html
3+
https://www.tpeczek.com/2019/04/fetch-api-streams-api-ndjson-and-aspnet.html
4+
https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_writable_streams

‎preclass/app/index.js

+33-36
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,15 @@
11
const API_URL = 'http://localhost:3000'
2-
async function* startConsumingAPI(signal) {
2+
3+
async function consumeAPI(signal) {
34
const response = await fetch(API_URL, {
45
signal
56
})
67

78
const reader = response.body
89
.pipeThrough(new TextDecoderStream())
910
.pipeThrough(parseNDJSON())
10-
.getReader()
1111

12-
let done = false
13-
do {
14-
const res = await reader.read()
15-
done = res.done
16-
if (done) break
17-
yield res.value
18-
}
19-
while (!done)
12+
return reader
2013
}
2114

2215
function parseNDJSON() {
@@ -38,37 +31,41 @@ function parseNDJSON() {
3831
})
3932
}
4033

41-
function appendToHTML({ title, description,url_anime, image }, el) {
42-
const card = `
43-
<article>
44-
<div class="text">
45-
<h3>${title}</h3>
46-
<p>${description.slice(0, 100)}</p>
47-
<a href="${url_anime}">Here's why</a>
48-
</div>
49-
</article>
50-
`
51-
el.innerHTML += card
34+
function appendToHTML(el) {
35+
return new WritableStream({
36+
async write({ title, description, url_anime }) {
37+
const card = `
38+
<article>
39+
<div class="text">
40+
<h3>[${++counter}] ${title}</h3>
41+
<p>${description.slice(0, 100)}</p>
42+
<a href="${url_anime}">Here's why</a>
43+
</div>
44+
</article>
45+
`
46+
el.innerHTML += card
47+
},
48+
abort(reason) {
49+
console.log('aborted**', reason)
50+
}
51+
})
5252
}
5353

54-
const [start, stop, cards] = ['Start', 'Stop', 'cards'].map(id => document.getElementById(id))
54+
const [
55+
start,
56+
stop,
57+
cards
58+
] = ['Start', 'Stop', 'cards']
59+
.map(
60+
id => document.getElementById(id)
61+
)
5562

5663
let abortController = new AbortController()
64+
let counter = 0
65+
5766
start.addEventListener('click', async () => {
58-
const it = startConsumingAPI(abortController.signal)
59-
let counter = 0
60-
try {
61-
for await (const item of it) {
62-
counter++
63-
console.log('item', counter, item.title)
64-
appendToHTML(item, cards)
65-
// if (counter >= 10) {
66-
// abortController.abort()
67-
// }
68-
}
69-
} catch (error) {
70-
if (!error.message.includes('aborted')) throw error
71-
}
67+
const reader = await consumeAPI(abortController.signal)
68+
reader.pipeTo(appendToHTML(cards))
7269
})
7370

7471
stop.addEventListener('click', () => {

‎preclass/server/server.js

+29-21
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
1-
/*
2-
echo "id,name,desc,age" > big.csv
3-
for i in `seq 1 1500`; do node -e "process.stdout.write('$i,erick-$i,'+'$i-text'.repeat(1e5)+',$i\n')" >> big.csv;done
4-
*/
51
import { createServer } from 'node:http'
62
import { createReadStream } from 'node:fs'
3+
import { setTimeout } from 'node:timers/promises'
4+
import { Transform, Readable } from 'node:stream'
5+
import { TransformStream, WritableStream } from 'node:stream/web'
76
import csvtojson from 'csvtojson'
8-
import { Transform } from 'node:stream'
97

108
const PORT = 3000
119
// curl -N localhost:3000
12-
createServer((request, response) => {
10+
createServer(async (request, response) => {
1311
const headers = {
1412
'Access-Control-Allow-Origin': '*',
1513
'Access-Control-Allow-Methods': '*',
@@ -22,30 +20,40 @@ createServer((request, response) => {
2220

2321
let items = 0
2422
request.once('close', () => console.log('connection was closed!', items))
25-
createReadStream('./animeflv.csv')
26-
.pipe(csvtojson())
27-
.pipe(Transform({
28-
transform(chunk, enc, cb) {
29-
items++
30-
const d = JSON.parse(chunk)
31-
setTimeout(() => {
32-
cb(
33-
null,
23+
24+
// const d = (await r.getReader().read()).value
25+
// console.log('d', Buffer.from(d).toString('utf8'))
26+
Readable.toWeb(createReadStream('./animeflv.csv'))
27+
.pipeThrough(Transform.toWeb(csvtojson()))
28+
.pipeThrough(
29+
new TransformStream({
30+
transform(chunk, controller) {
31+
const d = JSON.parse(Buffer.from(chunk))
32+
controller.enqueue(
3433
JSON.stringify({
3534
title: d.title,
3635
description: d.description,
3736
url_anime: d.url_anime,
3837
image: d.image
3938
}).concat('\n')
4039
)
41-
}, 200)
42-
43-
}
44-
}))
45-
.pipe(response)
40+
},
41+
})
42+
)
43+
.pipeTo(
44+
new WritableStream({
45+
async write(chunk) {
46+
await setTimeout(200)
47+
items++
48+
response.write(chunk)
49+
},
50+
close() {
51+
response.end()
52+
}
53+
})
54+
)
4655

4756
response.writeHead(200, headers)
48-
4957
})
5058
.listen(PORT)
5159
.on('listening', _ => console.log('server running at ', PORT))

0 commit comments

Comments
 (0)