-
Notifications
You must be signed in to change notification settings - Fork 0
/
useWikidata.js
34 lines (28 loc) · 993 Bytes
/
useWikidata.js
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
class SPARQLQueryDispatcher {
constructor( endpoint ) {
this.endpoint = endpoint;
}
query( sparqlQuery ) {
const fullUrl = this.endpoint + '?query=' + encodeURIComponent( sparqlQuery );
const headers = { 'Accept': 'application/sparql-results+json' };
return fetch( fullUrl, { headers } ).then( body => body.json() );
}
}
const endpointUrl = 'https://query.wikidata.org/sparql';
const queryDispatcher = new SPARQLQueryDispatcher( endpointUrl );
const wikidata = {
getLabelFromIATA: (iata) => {
const sparqlQuery = `
SELECT ?item ?itemLabel
WHERE
{
?item wdt:P238 '${iata.replaceAll('\'', "\\\'")}'.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}`;
return queryDispatcher.query( sparqlQuery ).then( json => {
return json.results.bindings[0]?.itemLabel.value ?? null;
});
}
};
const useWikidata = () => wikidata;
module.exports = { useWikidata };