-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample-node.mts
More file actions
70 lines (55 loc) · 2.03 KB
/
example-node.mts
File metadata and controls
70 lines (55 loc) · 2.03 KB
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
import { request } from 'node:https';
import { Buffer } from 'node:buffer';
import { EventEmitter } from 'node:events';
import { HttpCache, isResponse } from './source/index.mts';
import { nodeReadableToSlowDisposableIterable } from './source/clone-stream.mts';
const storage = new Map<string, any>();
const cache = new HttpCache(storage, storage);
const url = 'https://szmarczak.com';
const method = 'GET';
const requestTime = Date.now();
const req = request(url, {
method,
}, async (res) => {
const responseTime = Date.now();
void cache.onResponse(
url,
method,
res.statusCode!,
req.getHeaders(),
res.headers,
requestTime,
responseTime,
nodeReadableToSlowDisposableIterable(res, EventEmitter, EventEmitter.errorMonitor),
);
const buffer: Uint8Array[] = [];
res.on('data', (chunk: Uint8Array) => {
buffer.push(chunk);
});
res.once('end', async () => {
// The following is for demo only. Do not use artificial delays in production.
await Promise.resolve(); // readWeb resolves (for await) after this resolve because we got 'end' first
await Promise.resolve(); // readWeb resolved, but because we resumed first, #onResponse hasn't resumed yet
await Promise.resolve(); // FIN
// Instead, await cache.onResponse(...) - you will save 1 event loop microtask.
if (!storage.has(url)) {
throw 'missing response in cache';
}
const body = Buffer.concat(buffer);
const cached = await cache.get(url, method, req.getHeaders());
if (isResponse(cached)) {
if (cached.body === null) {
throw 'unexpected lack of body';
}
console.log(
body.length,
cached.body.length,
body.length === cached.body.length,
body.every((byte, index) => byte === cached.body![index]),
);
} else {
throw 'expected cached response';
}
});
});
req.end();