diff src/ViewConfig.ts @ 102:ab7dca42afbd

rewrite ViewConfig
author drewp@bigasterisk.com
date Fri, 11 Mar 2022 23:19:35 -0800
parents src/view_loader.ts@26c55d5d5202
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/ViewConfig.ts	Fri Mar 11 23:19:35 2022 -0800
@@ -0,0 +1,70 @@
+// Load requested view (rdf data) and provide access to it
+import { DataFactory, NamedNode, Store } from "n3";
+import { fetchAndParse, n3Graph } from "./fetchAndParse";
+import { EX, RDF } from "./namespaces";
+import { labelOrTail, uriValue } from "./rdf_value";
+const Uri = DataFactory.namedNode;
+
+function firstElem<E>(seq: Iterable<E>): E {
+  for (let e of seq) {
+    return e;
+  }
+  throw new Error("no elems");
+}
+
+export interface TableDesc {
+  uri: NamedNode;
+  primary: NamedNode;
+  joins: NamedNode[];
+}
+
+export class ViewConfig {
+  graph: Store;
+  viewRoot!: NamedNode;
+  url?: string;
+  tables: TableDesc[] = [];
+
+  constructor() {
+    this.graph = new Store();
+  }
+
+  async readFromUrl(url: string | "") {
+    if (!url) {
+      return;
+    }
+    await fetchAndParse(url, this.graph);
+
+    this._read();
+  }
+
+  async readFromGraph(n3: string) {
+    this.graph = await n3Graph(n3);
+    this._read();
+  }
+
+  _read() {
+    this.viewRoot = firstElem(
+      this.graph.getSubjects(RDF("type"), EX("View"), null)
+    ) as NamedNode;
+    for (let table of this.graph.getObjects(this.viewRoot, EX("table"), null)) {
+      const tableType = uriValue(this.graph, table, EX("primaryType"));
+      const joins: NamedNode[] = [];
+      for (let joinType of this.graph.getObjects(table, EX("joinType"), null)) {
+        joins.push(joinType as NamedNode);
+      }
+      joins.sort();
+      this.tables.push({
+        uri: table as NamedNode,
+        primary: tableType,
+        joins: joins,
+      });
+    }
+    this.tables.sort();
+  }
+
+  label(): string {
+    return this.url !== undefined
+      ? labelOrTail(this.graph, Uri(this.url))
+      : "unnamed";
+  }
+}