feat: search streaming fallback

This commit is contained in:
Ramires Viana 2025-12-21 19:38:09 -03:00
parent 9891e9db2d
commit 771170fe6c

View File

@ -19,21 +19,39 @@ export default async function search(
throw new StatusError("000 No connection", 0); throw new StatusError("000 No connection", 0);
} }
try { try {
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); // Try streaming approach first (modern browsers)
let buffer = ""; if (res.body && typeof res.body.pipeThrough === "function") {
while (true) { const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
const { done, value } = await reader.read(); let buffer = "";
if (value) { while (true) {
buffer += value; const { done, value } = await reader.read();
} if (value) {
const lines = buffer.split(/\n/); buffer += value;
let lastLine = lines.pop(); }
// Save incomplete last line const lines = buffer.split(/\n/);
if (!lastLine) { let lastLine = lines.pop();
lastLine = ""; // Save incomplete last line
} if (!lastLine) {
buffer = lastLine; lastLine = "";
}
buffer = lastLine;
for (const line of lines) {
if (line) {
const item = JSON.parse(line) as ResourceItem;
item.url = `/files${base}` + url.encodePath(item.path);
if (item.isDir) {
item.url += "/";
}
callback(item);
}
}
if (done) break;
}
} else {
// Fallback for browsers without streaming support (e.g., Safari)
const text = await res.text();
const lines = text.split(/\n/);
for (const line of lines) { for (const line of lines) {
if (line) { if (line) {
const item = JSON.parse(line) as ResourceItem; const item = JSON.parse(line) as ResourceItem;
@ -44,7 +62,6 @@ export default async function search(
callback(item); callback(item);
} }
} }
if (done) break;
} }
} catch (e) { } catch (e) {
// Check if the error is an intentional cancellation // Check if the error is an intentional cancellation