-
Notifications
You must be signed in to change notification settings - Fork 11
/
resource.ts
240 lines (201 loc) · 5.89 KB
/
resource.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
import Handlebars from "handlebars";
import fetch from "node-fetch";
import groupBy from "lodash.groupby";
import mapValues from "lodash.mapvalues";
import transform from "lodash.transform";
import { ObjectTypeDefinitionNode } from "graphql";
import { URLSearchParams } from "url";
import Resources from "./resources";
import {
oneOrMany,
isListType,
unwrapCompositeType,
ensureArray,
} from "./utils";
interface Triple {
s: string;
p: string;
o: string;
}
type CompiledTemplate = (args: object) => string;
export type ResourceEntry = Record<string, any>;
const handlebars = Handlebars.create();
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 = "";
enum State {
Default,
Endpoint,
Sparql,
}
let state: State = State.Default;
lines.forEach((line: string) => {
switch (line) {
case "--- endpoint ---":
state = State.Endpoint;
return;
case "--- sparql ---":
state = State.Sparql;
return;
}
switch (state) {
case State.Endpoint:
endpoint = line;
state = State.Default;
break;
case State.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: {
Accept: "application/sparql-results+json",
},
};
const res = await fetch(this.endpoint, opts);
if (res.ok) {
const data = (await res.json()) as any;
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);
});
} 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;
}
}