-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathresource.ts
More file actions
290 lines (243 loc) · 7.6 KB
/
resource.ts
File metadata and controls
290 lines (243 loc) · 7.6 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import Handlebars from "handlebars";
import groupBy from "lodash.groupby";
import mapValues from "lodash.mapvalues";
import transform from "lodash.transform";
import type { ObjectTypeDefinitionNode } from "graphql";
import Resources from "./resources.ts";
import {
oneOrMany,
isListType,
unwrapCompositeType,
ensureArray,
} from "./utils.ts";
interface Triple {
s: string;
p: string;
o: string;
}
type CompiledTemplate = (args: object) => string;
export type ResourceEntry = Record<string, any>;
const handlebars = Handlebars.create();
function decodeQleverValue(rawValue: string): string {
const iriMatch = rawValue.match(/^<(.+)>$/);
if (iriMatch) {
return iriMatch[1];
}
const literalMatch = rawValue.match(
/^"((?:[^"\\]|\\.)*)"(?:@[A-Za-z0-9-]+|\^\^<[^>]+>)?$/
);
if (literalMatch) {
return literalMatch[1]
.replace(/\\t/g, "\t")
.replace(/\\n/g, "\n")
.replace(/\\r/g, "\r")
.replace(/\\"/g, '"')
.replace(/\\\\/g, "\\");
}
return rawValue;
}
function normalizeBindings(data: any, contentType: string | null): Array<Triple> {
const normalizedContentType = (contentType || "").toLowerCase();
if (normalizedContentType.includes("application/sparql-results+json")) {
return data.results.bindings.map((b: Record<string, any>) => {
const normalizedBinding = {
s: b.s || b.subject,
p: b.p || b.predicate,
o: b.o || b.object,
};
return mapValues(normalizedBinding, ({ value }) => value);
});
}
if (normalizedContentType.includes("application/qlever-results+json")) {
const selected: string[] = data.selected;
const getIndex = (...names: string[]) =>
selected.findIndex((name) => names.includes(name));
const sIdx = getIndex("?s", "?subject");
const pIdx = getIndex("?p", "?predicate");
const oIdx = getIndex("?o", "?object");
if (sIdx < 0 || pIdx < 0 || oIdx < 0) {
throw new Error(
`QLever JSON result does not include ?s/?p/?o (selected=${selected.join(
", "
)})`
);
}
return data.res.map((row: string[]) => ({
s: decodeQleverValue(row[sIdx]),
p: decodeQleverValue(row[pIdx]),
o: decodeQleverValue(row[oIdx]),
}));
}
throw new Error(`Unsupported SPARQL content type: ${contentType}`);
}
handlebars.registerHelper(
"join",
function (separator: string, strs: string | string[]): string {
return ensureArray(strs).join(separator);
}
);
handlebars.registerHelper(
"as-iriref",
function (strs: string | string[]): string[] {
return ensureArray(strs).map((str) => `<${str}>`);
}
);
handlebars.registerHelper(
"as-string",
function (strs: string | string[]): string[] {
return ensureArray(strs).map((str) => `"${str}"`);
}
);
function buildEntry(
bindingsGroupedBySubject: Record<string, Array<Triple>>,
subject: string,
resource: Resource,
resources: Resources
): ResourceEntry {
const entry: ResourceEntry = {};
const pValues = transform(
bindingsGroupedBySubject[subject],
(acc, { p, o }: Triple) => {
const k = p.replace(/^https:\/\/github\.com\/dbcls\/grasp\/ns\//, "");
(acc[k] || (acc[k] = [])).push(o);
},
{} as Record<string, string[]>
);
(resource.definition.fields || []).forEach((field) => {
const type = field.type;
const name = field.name.value;
const values = pValues[name] || [];
const targetType = unwrapCompositeType(type);
const targetResource = resources.lookup(targetType.name.value);
if (targetResource?.isEmbeddedType) {
const entries = values.map((nodeId) =>
buildEntry(bindingsGroupedBySubject, nodeId, targetResource, resources)
);
entry[name] = oneOrMany(entries, !isListType(type));
} else {
entry[name] = oneOrMany(values, !isListType(type));
}
});
return entry;
}
export default class Resource {
resources: Resources;
definition: ObjectTypeDefinitionNode;
endpoint: string | null;
queryTemplate: CompiledTemplate | null;
constructor(
resources: Resources,
definition: ObjectTypeDefinitionNode,
endpoint: string | null,
sparql: string | null
) {
this.resources = resources;
this.definition = definition;
this.endpoint = endpoint;
this.queryTemplate = sparql
? handlebars.compile(sparql, { noEscape: true })
: null;
}
static buildFromTypeDefinition(
resources: Resources,
def: ObjectTypeDefinitionNode
): Resource {
if (
def.directives?.some((directive) => directive.name.value === "embedded")
) {
return new Resource(resources, def, null, null);
}
if (!def.description) {
throw new Error(`description for type ${def.name.value} is not defined`);
}
const description = def.description.value;
const lines = description.split(/\r?\n/);
let endpoint: string | null = null,
sparql = "";
let state: "default" | "endpoint" | "sparql" = "default";
lines.forEach((line: string) => {
switch (line) {
case "--- endpoint ---":
state = "endpoint";
return;
case "--- sparql ---":
state = "sparql";
return;
}
switch (state) {
case "endpoint":
endpoint = line;
state = "default";
break;
case "sparql":
sparql += line + "\n";
break;
}
});
if (!endpoint) {
throw new Error(`endpoint is not defined for type ${def.name.value}`);
}
return new Resource(resources, def, endpoint, sparql);
}
async fetch(args: object): Promise<ResourceEntry[]> {
const bindings = await this.query(args);
const bindingGropuedBySubject = groupBy(bindings, "s");
const primaryBindings = bindings.filter(
(binding) => !binding.s.startsWith("_:")
);
const entries = Object.entries(groupBy(primaryBindings, "s")).map(
([s, _sBindings]) => {
return buildEntry(bindingGropuedBySubject, s, this, this.resources);
}
);
return entries;
}
async fetchByIRIs(
iris: ReadonlyArray<string>
): Promise<Array<ResourceEntry | null>> {
const entries = await this.fetch({ iri: iris });
return iris.map(
(iri) => entries.find((entry) => entry.iri === iri) || null
);
}
async query(args: object): Promise<Array<Triple>> {
if (!this.queryTemplate || !this.endpoint) {
throw new Error(
"query template and endpoint should be specified in order to query"
);
}
const sparqlQuery = this.queryTemplate(args);
console.log("--- SPARQL QUERY ---", sparqlQuery);
const sparqlParams = new URLSearchParams();
sparqlParams.append("query", sparqlQuery);
const opts = {
method: "POST",
body: sparqlParams,
headers: {
// Keep this order for compatibility with both QLever and Virtuoso:
// Virtuoso may fail when `application/qlever-results+json` is listed first,
// but QLever needs `application/qlever-results+json` to return `CONSTRUCT` results as JSON.
Accept:
"application/sparql-results+json, application/qlever-results+json",
},
};
const res = await fetch(this.endpoint, opts);
if (res.ok) {
const data = (await res.json()) as any;
return normalizeBindings(data, res.headers.get("content-type"));
} else {
const body = await res.text();
throw new Error(
`SPARQL endpoint returns ${res.status} ${res.statusText}: ${body}`
);
}
}
get isRootType(): boolean {
return !this.definition.directives?.some(
(directive) => directive.name.value === "embedded"
);
}
get isEmbeddedType(): boolean {
return !this.isRootType;
}
}