1586
|
1 import { Literal, N3Store, Util, NamedNode, DataFactory } from "n3";
|
|
2 const { literal, namedNode } = DataFactory;
|
|
3
|
|
4 // workaround for uris that don't have good labels in the graph
|
|
5 export function labelFromUri(
|
|
6 uri: NamedNode,
|
|
7 prefix: string,
|
|
8 tailsToLabels: { [key: string]: string },
|
|
9 defaultLabel: string
|
|
10 ) {
|
|
11 let label = defaultLabel === undefined ? uri.value : defaultLabel;
|
|
12 Object.entries(tailsToLabels).forEach(([tail, useLabel]) => {
|
|
13 if (uri.equals(namedNode(prefix + tail))) {
|
|
14 label = useLabel as string;
|
|
15 }
|
|
16 });
|
|
17 return label;
|
|
18 }
|
|
19
|
|
20 export function graphLiteral(
|
|
21 store: N3Store,
|
|
22 subj: NamedNode,
|
|
23 pred: string,
|
|
24 notFoundResult?: string
|
|
25 ): Literal {
|
|
26 const keep: Array<Literal> = [];
|
|
27 store.forEach(
|
|
28 q => {
|
|
29 if (!Util.isLiteral(q.object)) {
|
|
30 throw new Error("non literal found");
|
|
31 }
|
|
32 let seen = false;
|
|
33 for (let other of keep) {
|
|
34 // why are we getting multiple matches for the same literal? seems like a bug
|
|
35 if (other.equals(q.object)) {
|
|
36 seen = true;
|
|
37 }
|
|
38 }
|
|
39 if (!seen) {
|
|
40 keep.push(q.object as Literal);
|
|
41 }
|
|
42 },
|
|
43 subj,
|
|
44 namedNode(pred),
|
|
45 null,
|
|
46 null
|
|
47 );
|
|
48 if (keep.length == 0) {
|
|
49 return literal(notFoundResult || "(missing)");
|
|
50 }
|
|
51 if (keep.length == 1) {
|
|
52 return keep[0];
|
|
53 }
|
|
54 console.log(`${subj.value} ${pred} had ${keep.length} objects:`, keep);
|
|
55 return keep[0];
|
|
56 }
|
|
57
|
|
58 export function graphUriValue(
|
|
59 store: N3Store,
|
|
60 subj: NamedNode,
|
|
61 pred: string
|
|
62 ): NamedNode | undefined {
|
|
63 const keep: Array<NamedNode> = [];
|
|
64 store.forEach(
|
|
65 q => {
|
|
66 if (!Util.isNamedNode(q.object)) {
|
|
67 throw new Error("non uri found");
|
|
68 }
|
|
69 keep.push(q.object as NamedNode);
|
|
70 },
|
|
71 subj,
|
|
72 namedNode(pred),
|
|
73 null,
|
|
74 null
|
|
75 );
|
|
76 if (keep.length == 0) {
|
|
77 return undefined;
|
|
78 }
|
|
79 if (keep.length == 1) {
|
|
80 return keep[0];
|
|
81 }
|
|
82 throw new Error("found multiple matches for pred");
|
|
83 }
|