Skip to content

Instantly share code, notes, and snippets.

@asrorbekh
Created December 18, 2024 19:48
Show Gist options
  • Save asrorbekh/2b51ef25bbf964278aa2583f96a6e380 to your computer and use it in GitHub Desktop.
Save asrorbekh/2b51ef25bbf964278aa2583f96a6e380 to your computer and use it in GitHub Desktop.
<script>
class CustomEventStream {
constructor(url, headers) {
this.url = url;
this.headers = headers;
this.reader = null;
this.decoder = new TextDecoder("utf-8");
}
async start(callback) {
try {
const response = await fetch(this.url, { headers: this.headers });
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
this.reader = response.body.getReader();
while (true) {
const { value, done } = await this.reader.read();
if (done) break;
const chunk = this.decoder.decode(value);
const lines = chunk.split("\n");
for (const line of lines) {
if (line.startsWith("data:")) {
const data = JSON.parse(line.slice(5).trim());
callback(data);
}
}
}
} catch (error) {
console.error("Stream error:", error);
} finally {
this.stop();
}
}
stop() {
if (this.reader) {
this.reader.cancel();
this.reader = null;
}
console.log("Stream stopped.");
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment