Skip to content

Instantly share code, notes, and snippets.

@RayBB
Created May 21, 2024 11:02
Show Gist options
  • Save RayBB/9bc329cfb4f9b1833747509a1e8e04b3 to your computer and use it in GitHub Desktop.
Save RayBB/9bc329cfb4f9b1833747509a1e8e04b3 to your computer and use it in GitHub Desktop.
/*
A script to auto generate this page: https://openlibrary.org/collections/kingdom-of-hawai'i-people
*/
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 sparqlQuery = `#People with Kingdom of Hawaii citizenship, or born there
SELECT distinct ?item ?itemLabel ?description ?wikipedia_url ?OLID
WHERE
{
?item wdt:P31 wd:Q5. #instance of (P31) human (Q5)
?item wdt:P648 ?OLID. # with open library ID
{
# Country of citizenship is Kingdom of Hawai'i
?item wdt:P27 wd:Q156418.
}UNION{
# Place of birth set to Kingdom of Hawaii
?item wdt:P19/wdt:P279* wd:Q156418.
}UNION{
# Place of birth with a country qualifier of Kingdom of Hawaii
?item p:P19 [pq:P17 wd:Q156418].
}
SERVICE wikibase:label {
bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
?item rdfs:label ?itemLabel;
schema:description ?description.
}
OPTIONAL {
?wikipedia_url schema:about ?item;
schema:inLanguage "en";
schema:isPartOf <https://en.wikipedia.org/>.
}
}`;
const queryDispatcher = new SPARQLQueryDispatcher(endpointUrl);
queryDispatcher.query(sparqlQuery).then(handleResponse);
function handleResponse(data) {
console.log(data);
const items = data.results.bindings;
// Sort based on smallest OLID
const sorted = items.sort((a, b) => {
const aValue = parseInt(a.OLID.value.match(/\d+/)[0]);
const bValue = parseInt(b.OLID.value.match(/\d+/)[0]);
return aValue - bValue;
});
console.log(sorted);
const carousels = sorted.map((e) => {
return makeCarousel(
e.OLID.value,
e.itemLabel?.value,
e.description?.value,
e.wikipedia_url?.value
);
});
console.log(carousels.join("\n\n"));
}
function makeCarousel(author_key, author_name, description, wikipedia_url) {
const wikipedia_anchor = wikipedia_url
? `<a href="${wikipedia_url}">Wikipedia</a>`
: "";
return `<a href="https://openlibrary.org/authors/${author_key}/">${author_name}</a> - ${description}. ${wikipedia_anchor}
{{QueryCarousel('author_key:${author_key}', has_fulltext_only=False)}}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment