Skip to content

Commit 1a5c705

Browse files
authored
feat: avoid refetch each time we read a file from an external source (#55)
1 parent 1710c7f commit 1a5c705

2 files changed

Lines changed: 15 additions & 10 deletions

File tree

src/__tests__/FileCollection.source.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ describe('fileCollectionFromWebSource', () => {
8585

8686
await firstFile.text();
8787

88-
// no cache it is reloaded a second time
89-
expect(fileRequestedCounter).toBe(2);
88+
// FileCollection must not fetch the file again
89+
expect(fileRequestedCounter).toBe(1);
9090

9191
const second = await secondFile.arrayBuffer();
9292

src/append/sourceItemToExtendedSourceItem.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ export function sourceItemToExtendedSourceItem(
1616
}
1717

1818
const fileURL = new URL(entry.relativePath, baseURL);
19+
let _blobPromise: Promise<Blob> | undefined;
20+
async function getBlobCached() {
21+
if (!_blobPromise) _blobPromise = fetch(fileURL).then((r) => r.blob());
22+
23+
return _blobPromise;
24+
}
25+
1926
return {
2027
uuid: entry.uuid ?? crypto.randomUUID(),
2128
name: entry.relativePath.split('/').pop() || '',
@@ -25,12 +32,12 @@ export function sourceItemToExtendedSourceItem(
2532
relativePath: entry.relativePath,
2633
lastModified: entry.lastModified,
2734
text: async (): Promise<string> => {
28-
const response = await fetch(fileURL.toString());
29-
return response.text();
35+
const blob = await getBlobCached();
36+
return blob.text();
3037
},
3138
arrayBuffer: async (): Promise<ArrayBuffer> => {
32-
const response = await fetch(fileURL.toString());
33-
return response.arrayBuffer();
39+
const blob = await getBlobCached();
40+
return blob.arrayBuffer();
3441
},
3542
stream: () => {
3643
const { writable, readable } = new TransformStream<
@@ -46,10 +53,8 @@ export function sourceItemToExtendedSourceItem(
4653
}
4754

4855
async function pipeFetchToStream() {
49-
const response = await fetch(fileURL.toString());
50-
// Should not be null
51-
const body = response.body as ReadableStream<Uint8Array>;
52-
await body.pipeTo(writable);
56+
const blob = await getBlobCached();
57+
await blob.stream().pipeTo(writable);
5358
}
5459

5560
void pipeFetchToStream().catch(propagateErrorToStream);

0 commit comments

Comments
 (0)