Skip to content

Commit

Permalink
Handler AbortError when reading stream using Fetch API
Browse files Browse the repository at this point in the history
  • Loading branch information
Tiscs committed Jan 8, 2024
1 parent d40d8ec commit 79e6b13
Showing 1 changed file with 17 additions and 17 deletions.
34 changes: 17 additions & 17 deletions app/clients/grpc.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,17 @@ export async function* fetchStream<I extends Message<I>, O extends Message<O>>(
mn: string,
rs: AbortSignal | null = null,
): AsyncGenerator<O> {
const resp = await fetch(`${window.env.GOMMERCE_GRPC_ENDPOINT}/${sn}/${mn}`, {
method: "POST",
body: req.toJsonString(),
headers: { "Content-Type": "application/json" },
signal: rs,
});
const decoder = new TextDecoder("utf-8");
const reader = resp.body?.getReader();
let buffer = "";
while (reader) {
try {
try {
const resp = await fetch(`${window.env.GOMMERCE_GRPC_ENDPOINT}/${sn}/${mn}`, {
method: "POST",
body: req.toJsonString(),
headers: { "Content-Type": "application/json" },
signal: rs,
});
const decoder = new TextDecoder("utf-8");
const reader = resp.body?.getReader();
let buffer = "";
while (reader) {
const { done, value } = await reader.read();
if (value && value.length > 0) {
buffer += decoder.decode(value);
Expand All @@ -54,17 +54,17 @@ export async function* fetchStream<I extends Message<I>, O extends Message<O>>(
const chunks = buffer.split(/\r?\n/);
buffer = chunks.pop() || "";
for (const chunk of chunks) {
yield mt.fromJsonString(chunk);
yield mt.fromJson(JSON.parse(chunk).result);
}
}
if (done) {
break;
}
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") {
break;
}
throw err;
}
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") {
return;
}
throw err;
}
}

0 comments on commit 79e6b13

Please sign in to comment.