UNPKG

@brimdata/zealot

Version:

The Javascript Client for Zed Lakes

126 lines (125 loc) 3.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "ResultStream", { enumerable: true, get: ()=>ResultStream }); const _lines = require("../ndjson/lines"); const _channel = require("./channel"); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } class ResultStream { get body() { return this.resp.body; } get promise() { return this.consume(); } get channels() { return Array.from(this.channelsMap.values()); } get shapes() { return this.channel(0).shapes; } get rows() { return this.channel(0).rows; } channel(id = this.currentChannelId) { if (id === undefined) throw new Error("Current channel not set"); let channel = this.channelsMap.get(id); if (!channel) { channel = new _channel.Channel(); this.channelsMap.set(id, channel); } return channel; } async js(opts = {}) { this.consume(); const channel = this.channel(0); await this.promise; return channel.rows.map((r)=>r.toJS(opts)); } async zed() { this.consume(); const channel = this.channel(0); await this.promise; return channel.rows; } collect(collector) { this.consume(); this.channel(0).collect(collector); return this.promise; } abort() { this.ctl.abort(); } consume() { if (this._promise) return this._promise; this.status = "pending"; // eslint-disable-next-line this._promise = new Promise(async (resolve, reject)=>{ try { for await (let json of (0, _lines.eachLine)(this.resp.body)){ this.consumeLine(json); } this.status = "success"; resolve(); } catch (e) { if (e instanceof DOMException && e.message.match(/user aborted/) || e instanceof Error && e.message.match(/context canceled/)) { this.status = "aborted"; reject(e); } else { this.status = "error"; reject(e); } } }); } consumeLine(json) { switch(json.type){ case "QueryChannelSet": this.currentChannelId = json.value.channel_id; break; case "QueryChannelEnd": this.currentChannelId = json.value.channel_id; var channel = this.channel(); channel.done(); break; case "QueryStats": break; case "QueryError": throw new Error(json.value.error); default: if (typeof json.type === "object") { this.channel().consume(json); break; } console.error("Unknown zjson object", json); } } constructor(resp, ctl){ _defineProperty(this, "resp", void 0); _defineProperty(this, "ctl", void 0); _defineProperty(this, "status", void 0); _defineProperty(this, "currentChannelId", void 0); _defineProperty(this, "channelsMap", void 0); _defineProperty(this, "_promise", void 0); this.resp = resp; this.ctl = ctl; this.status = "idle"; this.channelsMap = new Map(); } }