-
Notifications
You must be signed in to change notification settings - Fork 4
/
DataToGraph.ts
168 lines (145 loc) · 5.71 KB
/
DataToGraph.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import rdfFactory, { Literal, LowLevelStore, NamedNode, Node, TermType } from "@ontologies/core";
import rdf from "@ontologies/rdf";
import ll from "../ontology/ll";
import RDFIndex from "../store/RDFIndex";
import {
DataObject,
DataTuple,
NamedBlobTuple,
NamespaceMap,
ParsedObject,
SerializableDataTypes,
SomeNode,
} from "../types";
import { MAIN_NODE_DEFAULT_IRI, NON_DATA_OBJECTS_CTORS } from "../utilities/constants";
import { expandProperty } from "../utilities/memoizedNamespace";
const BASE = 36;
const DEC_CUTOFF = 2;
const IRI_LEN = 20;
function isPlainObject(o: any): o is DataObject {
return typeof o === "object"
&& o !== null
&& !NON_DATA_OBJECTS_CTORS.find((c) => typeof o.prototype !== "undefined" && o instanceof c)
&& !Object.prototype.hasOwnProperty.call(o, "termType");
}
function isIterable(o: any): o is any[] | Set<any> {
return Array.isArray(o) || o instanceof Set;
}
function uploadIRI(): NamedNode {
return ll.ns(`blobs/a${Math.random().toString(BASE).substr(DEC_CUTOFF, IRI_LEN)}`);
}
/**
* Converts an array to an RDF list-shaped {DataObject} for serialization.
*/
export function list(arr: SerializableDataTypes[]): DataObject {
// @ts-ignore
return arr.reduceRight((acc: DataObject, next: SerializableDataTypes) => ({
[rdf.first.toString()]: next,
[rdf.rest.toString()]: acc,
}), rdf.nil);
}
/**
* Converts an array to an RDF sequence-shaped {DataObject} for serialization.
*/
export function seq<T = any>(arr: T[], id?: SomeNode): DataObject {
const base: DataObject = { [rdf.type.toString()]: rdf.Seq };
if (id) {
base["@id"] = id;
}
return arr.reduce(
(acc, next, n) => Object.assign(acc, { [rdf.ns(`_${n}`).toString()]: next }),
base,
);
}
/** @private */
export function processObject(subject: Node,
predicate: NamedNode,
datum: DataObject | SerializableDataTypes | null | undefined,
store: LowLevelStore,
ns?: NamespaceMap): NamedBlobTuple[] {
let blobs: NamedBlobTuple[] = [];
if (isIterable(datum)) {
for (const subResource of datum) {
blobs = blobs.concat(processObject(subject, predicate, subResource, store, ns));
}
} else if (typeof datum === "string"
|| typeof datum === "number"
|| typeof datum === "boolean"
|| datum instanceof Date) {
store.add(subject, predicate, rdfFactory.literal(datum));
} else if (datum instanceof File) {
const f = uploadIRI();
const file = rdfFactory.quad(subject, predicate, f);
blobs.push([f, datum as File]);
store.addQuad(file);
} else if (isPlainObject(datum)) {
const id = datum["@id"] as SomeNode | undefined || rdfFactory.blankNode();
blobs = blobs.concat(processDataObject(id, datum, store, ns));
store.add(subject, predicate, id);
} else if (datum && datum.termType === TermType.NamedNode) {
store.add(subject, predicate, rdfFactory.namedNode(datum.value));
} else if (datum && datum.termType === TermType.Literal) {
store.add(
subject,
predicate,
rdfFactory.literal(
datum.value,
(datum as Literal).language || rdfFactory.namedNode((datum as Literal).datatype.value),
),
);
} else if (datum !== null && datum !== undefined) {
store.add(subject, predicate, rdfFactory.literal(datum));
}
return blobs;
}
function processDataObject(subject: Node, data: DataObject, store: LowLevelStore, ns?: NamespaceMap): NamedBlobTuple[] {
let blobs: NamedBlobTuple[] = [];
const keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
if (keys[i] === "@id") { continue; }
const predicate = expandProperty(keys[i], ns || {});
const datum = data[keys[i]];
if (predicate === undefined) {
throw new Error(`Unknown predicate ${keys[i]} given (for subject '${subject}').`);
}
blobs = blobs.concat(processObject(subject, predicate, datum, store, ns));
}
return blobs;
}
export function dataToGraphTuple(data: DataObject, ns?: NamespaceMap): DataTuple {
const store = new RDFIndex();
const blobs = processDataObject(MAIN_NODE_DEFAULT_IRI, data, store, ns);
return [store, blobs];
}
/**
* Convert a DataObject into a graph. Useful for writing test data in semi-plain JS objects
* @param iriOrData The data object or an iri for the top-level object.
* @param data The data object if an IRI was passed.
* @param store A graph to write the statements into.
* @param ns Namespace mapping for converting shortened keys.
*/
export function toGraph(
iriOrData: SomeNode | DataObject,
data?: DataObject,
store?: LowLevelStore,
ns?: NamespaceMap,
): ParsedObject {
const passedIRI = iriOrData.termType === TermType.BlankNode || iriOrData.termType === TermType.NamedNode;
if (passedIRI && !data) {
throw new TypeError("Only an IRI was passed to `toObject`, a valid data object has to be the second argument");
}
const embeddedIRI = ((passedIRI ? data : iriOrData) as DataObject)!["@id"];
let iri;
if (embeddedIRI) {
if (typeof embeddedIRI !== "string") {
throw new TypeError("Embedded IRI (`@id`) value must be of type string");
}
iri = rdfFactory.namedNode(embeddedIRI);
} else {
iri = passedIRI ? (iriOrData as SomeNode) : rdfFactory.blankNode();
}
const dataObj = passedIRI ? data! : (iriOrData as DataObject);
const s = store || new RDFIndex();
const blobs = processDataObject(iri, dataObj, s, ns);
return [iri, s, blobs];
}