SystemQueryClient: Add generator for fetching tables via SSE

This commit is contained in:
Starbeamrainbowlabs 2022-02-25 03:22:58 +00:00
parent a62c8e6b4e
commit b1f6a44a6a
Signed by: sbrl
GPG key ID: 1BE5172E637709C2
2 changed files with 44 additions and 0 deletions

View file

@ -1,5 +1,7 @@
"use strict";
import { once } from './misc/events.mjs';
class SystemQueryClient {
constructor() {
@ -9,6 +11,26 @@ class SystemQueryClient {
return this.fetch_json(`/api/status`);
}
async *table(table_name) {
const abort = new AbortController();
const source = new EventSource(`/api/table/${table_name}`);
source.addEventListener(`end`, () => {
source.close();
abort.abort();
}, { once: true });
let count = 0;
while(source.readyState !== EventSource.CLOSED) {
let item = await once(source, "table", abort.signal);
if(item.type === "abort") break;
yield JSON.parse(item.data);
count++;
}
console.log(`FETCH TABLE ${table_name}: ${count} items returned`);
}
async fetch_json(path) {
let response = await fetch(path, {
headers: {

View file

@ -0,0 +1,22 @@
"use strict";
function once(event_emitter, event_name, abort_signal = null) {
return new Promise((resolve, reject) => {
let options = {
once: true
};
if(abort_signal !== null) options.signal = abort_signal;
let resolve_handler = function() {
event_emitter.removeEventListener("error", reject);
abort_signal.removeEventListener("abort", resolve_handler);
resolve(...arguments);
};
abort_signal.addEventListener("abort", resolve_handler);
event_emitter.addEventListener("error", reject, options);
event_emitter.addEventListener(event_name, resolve_handler, options);
});
}
export { once };