view src/ViewConfig.ts @ 103:f12feced00ce

WIP rewriting Layout
author drewp@bigasterisk.com
date Sat, 12 Mar 2022 00:42:00 -0800
parents ab7dca42afbd
children
line wrap: on
line source

// 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";
  }
}