Mercurial > code > home > repos > homeauto
comparison service/wifi/src/graph_access.ts @ 1480:ae023bba2104
refactor plain graph functions from lit-element
Ignore-this: db67b7d211f72ba9d14b0d490f7dc9da
darcs-hash:88cdb343d3f5e47f06e2737402ef48257b0f80e9
author | drewp <drewp@bigasterisk.com> |
---|---|
date | Mon, 06 Jan 2020 22:39:46 -0800 |
parents | |
children | 50d66febeeb0 |
comparison
equal
deleted
inserted
replaced
1479:ad9ec466ba6d | 1480:ae023bba2104 |
---|---|
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 if (other.equals(q.object)) { | |
35 seen = true; | |
36 } | |
37 } | |
38 if (!seen) { | |
39 keep.push(q.object as Literal); | |
40 } | |
41 }, | |
42 subj, | |
43 namedNode(pred), | |
44 null, | |
45 null | |
46 ); | |
47 if (keep.length == 0) { | |
48 return literal(notFoundResult || "(missing)"); | |
49 } | |
50 if (keep.length == 1) { | |
51 return keep[0]; | |
52 } | |
53 console.log(`${subj.value} ${pred} had ${keep.length} objects:`, keep); | |
54 return keep[0]; | |
55 } | |
56 | |
57 export function graphUriValue( | |
58 store: N3Store, | |
59 subj: NamedNode, | |
60 pred: string | |
61 ): NamedNode | undefined { | |
62 const keep: Array<NamedNode> = []; | |
63 store.forEach( | |
64 q => { | |
65 if (!Util.isNamedNode(q.object)) { | |
66 throw new Error("non uri found"); | |
67 } | |
68 keep.push(q.object as NamedNode); | |
69 }, | |
70 subj, | |
71 namedNode(pred), | |
72 null, | |
73 null | |
74 ); | |
75 if (keep.length == 0) { | |
76 return undefined; | |
77 } | |
78 if (keep.length == 1) { | |
79 return keep[0]; | |
80 } | |
81 throw new Error("found multiple matches for pred"); | |
82 } |