-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPARQL.js
More file actions
64 lines (63 loc) · 1.84 KB
/
Copy pathSPARQL.js
File metadata and controls
64 lines (63 loc) · 1.84 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
class SPARQL {
constructor(baseurl) {
this.baseurl = baseurl;
}
async sparql(query) {
const url = `${this.baseurl}?query=${encodeURIComponent(query)}`;
const json = await (await fetch(url)).json();
return json;
}
err(json) {
throw new Error(JSON.stringify(json, 2, null));
}
async sparqlItem(query) {
const json = await this.sparql(query);
if (!json.results) {
throw this.err(json);
}
return json.results.bindings[0];
}
async sparqlItems(query) {
const json = await this.sparql(query);
if (!json.results) {
throw this.err(json);
}
return json.results.bindings;
}
values(json) {
const name = json.head.vars[0];
return json.results.bindings.map((d) => d[name].value);
}
cutType(json) {
if (!json) {
return null;
}
if (Array.isArray(json)) {
return json.map((d) => this.cutType(d));
} else {
const d = json;
Object.keys(d).forEach((key) => d[key] = d[key].value);
return d;
}
}
async getTypes() {
const query = "select distinct ?o { ?s a ?o. } order by ?o";
return this.values(await this.sparql(query));
}
async getProperties() {
const query = `select distinct ?p { ?s ?p ?o. } order by ?p`;
return this.values(await this.sparql(query));
}
async getItems(uri, n = 10) {
//const query = `select ?s { ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <${uri}>. } order by rand() limit 10`;
//const query = `select ?s { ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <${uri}>. } limit 10`;
const query =
`select ?p ?o { ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <${uri}>. ?s ?p ?o } limit ${n}`;
return await this.sparql(query);
}
async getItem(uri) {
const query = `select * { <${uri}> ?p ?o. }`;
return await this.sparql(query);
}
}
export { SPARQL };