-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
decoder.ts
246 lines (215 loc) · 7 KB
/
decoder.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { type Context, fromRdf, Graph, Iri, Node, type RDF } from "./rdf.ts";
import type { Property, Schema } from "./schema/mod.ts";
import ldkit from "./namespaces/ldkit.ts";
import rdf from "./namespaces/rdf.ts";
type DecodedNode = Record<string, unknown>;
class Decoder {
private graph: Graph;
private schema: Schema;
private context: Context;
private cache: Map<Schema, Map<Iri, DecodedNode>> = new Map();
private constructor(graph: Graph, schema: Schema, context: Context) {
this.graph = graph;
this.schema = schema;
this.context = context;
}
static decode(graph: Graph, schema: Schema, context: Context) {
return new Decoder(graph, schema, context).decode();
}
getCachedNode(nodeIri: Iri, schema: Schema) {
if (!this.cache.has(schema)) {
this.cache.set(schema, new Map());
}
return this.cache.get(schema)!.get(nodeIri);
}
setCachedNode(nodeIri: Iri, schema: Schema, decodedNode: DecodedNode) {
if (!this.cache.has(schema)) {
this.cache.set(schema, new Map());
}
this.cache.get(schema)!.set(nodeIri, decodedNode);
}
decode() {
const output: DecodedNode[] = [];
for (const [iri, properties] of this.graph) {
if (properties.has(rdf.type)) {
const types = properties.get(rdf.type)!;
for (const type of types) {
if (type.termType === "NamedNode" && type.value === ldkit.Resource) {
output.push(this.decodeNode(iri, this.schema));
}
}
}
}
if (this.graph.size > 0 && output.length < 1) {
throw new Error(
`Unable to decode graph - no resources with type <${ldkit.Resource}> found`,
);
}
return output;
}
decodeNode(nodeIri: Iri, schema: Schema) {
const cachedNode = this.getCachedNode(nodeIri, schema);
if (cachedNode) {
return cachedNode;
}
const output: DecodedNode = {
$id: nodeIri,
};
const node = this.graph.get(nodeIri);
if (!node) {
throw new Error(`Error decoding graph, <${nodeIri}> node not found.`);
}
output.$type = this.decodeNodeType(node);
Object.keys(schema).forEach((key) => {
if (key === "@type") {
return;
}
const result = this.decodeNodeProperty(
nodeIri,
node,
key,
schema[key] as Property,
);
if (result !== undefined) {
output[key] = result;
}
});
this.setCachedNode(nodeIri, schema, output);
return output;
}
decodeNodeType(node: Node) {
const typeTerms = node.get(rdf.type);
if (!typeTerms) {
return [];
}
return typeTerms.reduce((acc, term) => {
if (term.value !== ldkit.Resource) {
acc.push(term.value);
}
return acc;
}, [] as Iri[]);
}
decodeNodeProperty(
nodeIri: Iri,
node: Node,
propertyKey: string,
property: Property,
) {
const terms = node.get(property["@id"]);
if (!terms) {
if (!property["@optional"]) {
// No data, required property
throw new Error(
`Required property "${propertyKey}" of type <${
property["@id"]
}> not found on resource <${nodeIri}>`,
);
} else {
// No data, optional property
return property["@array"] ? [] : undefined;
}
}
if (property["@multilang"]) {
if (property["@array"]) {
return terms.reduce((acc, term) => {
if (term.termType !== "Literal") {
throw new Error(
`Property "${propertyKey}" data type mismatch - expected a literal, but received ${term.termType} instead on resource <${nodeIri}>`,
);
}
const language = term.language;
if (!acc[language]) {
acc[language] = [];
}
acc[language].push(this.decodeTerm(term));
return acc;
}, {} as Record<string, string[]>);
} else {
return terms.reduce((acc, term) => {
if (term.termType !== "Literal") {
throw new Error(
`Property "${propertyKey}" data type mismatch - expected a literal, but received ${term.termType} instead on resource <${nodeIri}>`,
);
}
const language = term.language;
if (!acc[language]) {
// If there are multiple strings with the same language detected, selecting only the first one
acc[language] = this.decodeTerm(term);
}
return acc;
}, {} as Record<string, string>);
}
}
if (property["@array"]) {
if (property["@context"]) {
// Collection of resources specified by sub schema
return terms.map((term) => {
if (term.termType !== "NamedNode" && term.termType !== "BlankNode") {
throw new Error(
`Property "${propertyKey}" data type mismatch - expected a node, but received ${term.termType} instead on resource <${nodeIri}>`,
);
}
return this.decodeNode(term.value, property["@context"]!);
});
} else {
// Collection of literals or named nodes
return terms.map((term) => {
if (term.termType !== "Literal" && term.termType !== "NamedNode") {
throw new Error(
`Property "${propertyKey}" data type mismatch - expected a literal or named node, but received ${term.termType} instead on resource <${nodeIri}>`,
);
}
return this.decodeTerm(term);
});
}
}
// Single return value expected from this point on
if (property["@context"]) {
for (const term of terms) {
if (term.termType === "NamedNode" || term.termType === "BlankNode") {
return this.decodeNode(term.value, property["@context"]!);
}
}
throw new Error(
`Property "${propertyKey}" data type mismatch - expected a named node for context on resource <${nodeIri}>`,
);
}
const preferredLanguage = this.context.language;
if (preferredLanguage) {
// Try to find a term that corresponds to the preferred language
for (const term of terms) {
if (
term.termType === "Literal" &&
term.language === preferredLanguage
) {
return this.decodeTerm(term);
}
}
}
// All options exhausted - return first namedNode or literal if there are multiple
for (const term of terms) {
if (term.termType === "Literal" || term.termType === "NamedNode") {
return this.decodeTerm(term);
}
}
throw new Error(
`Property "${propertyKey}" data type mismatch - expected a literal or named node instead on resource <${nodeIri}>`,
);
}
decodeTerm(term: RDF.Term) {
if (term.termType === "NamedNode") {
return term.value;
} else if (term.termType === "Literal") {
return fromRdf(term);
} else {
throw new Error(`Unsupported term type to resolve: ${term.termType}`);
}
}
}
export const decode = (
graph: Graph,
schema: Schema,
context: Context,
) => {
return Decoder.decode(graph, schema, context);
};