UNPKG

@bokeh/bokehjs

Version:

Interactive, novel data visualization

69 lines 2.57 kB
import { WebDataSource } from "./web_data_source"; import { HTTPMethod } from "../../core/enums"; import { logger } from "../../core/logging"; import { entries } from "../../core/util/object"; export class AjaxDataSource extends WebDataSource { static __name__ = "AjaxDataSource"; constructor(attrs) { super(attrs); } static { this.define(({ Bool, Int, Str, Dict, Nullable }) => ({ polling_interval: [Nullable(Int), null], content_type: [Str, "application/json"], http_headers: [Dict(Str), {}], method: [HTTPMethod, "POST"], if_modified: [Bool, false], })); } // TODO don't use initializers until https://github.com/bokeh/bokeh/issues/13732 is fixed interval; initialized; last_fetch_time; destroy() { if (this.interval != null) { clearInterval(this.interval); } super.destroy(); } setup() { if (this.initialized !== true) { this.initialized = true; this.get_data(this.mode); if (this.polling_interval != null) { const callback = () => this.get_data(this.mode, this.max_size, this.if_modified); this.interval = setInterval(callback, this.polling_interval); } } } get_data(mode, max_size = null, if_modified = false) { const xhr = this.prepare_request(); xhr.addEventListener("load", () => this.do_load(xhr, mode, max_size ?? undefined)); xhr.addEventListener("error", () => this.do_error(xhr)); if (if_modified && this.last_fetch_time != null) { xhr.setRequestHeader("If-Modified-Since", this.last_fetch_time.toUTCString()); } xhr.send(); } prepare_request() { const xhr = new XMLHttpRequest(); xhr.open(this.method, this.data_url, true); xhr.withCredentials = false; xhr.setRequestHeader("Content-Type", this.content_type); for (const [name, value] of entries(this.http_headers)) { xhr.setRequestHeader(name, value); } return xhr; } async do_load(xhr, mode, max_size) { if (xhr.status == 200) { const raw_data = JSON.parse(xhr.responseText); this.last_fetch_time = new Date(); await this.load_data(raw_data, mode, max_size); } } do_error(xhr) { logger.error(`Failed to fetch JSON from ${this.data_url} with code ${xhr.status}`); } } //# sourceMappingURL=ajax_data_source.js.map