From b0d267c6b311e98821aed98cf99f74fe8866b6f0 Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Tue, 13 Feb 2024 21:21:43 +0100 Subject: [PATCH] feat: Add a SPARQL query to retrieve images from Wikimedia commons --- controllers/wikidata.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 controllers/wikidata.js diff --git a/controllers/wikidata.js b/controllers/wikidata.js new file mode 100644 index 0000000..128e922 --- /dev/null +++ b/controllers/wikidata.js @@ -0,0 +1,28 @@ +// Query wikidata with axios +const axios = require("axios"); + +function query(sparqlQuery) { + const endpoint = 'https://query.wikidata.org/sparql'; + const fullUrl = endpoint + '?query=' + encodeURIComponent( sparqlQuery ); + const headers = { 'Accept': 'application/sparql-results+json' }; + return axios.get(fullUrl, { headers }).then( body => body.data ); +} + +function encodeSparqlQuery(species) { + let sparqlTemplate = `#defaultView:ImageGrid + SELECT ?item ?itemLabel ?pic + WHERE + { + ?item wdt:P225 "${species}" . + ?item wdt:P18 ?pic + SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" } + }` + return sparqlTemplate; +} + + +function getPictures(species) { + return query(encodeSparqlQuery(species)); +} + +getPictures("Picus viridis").then((data) => console.log(data.results.bindings)); \ No newline at end of file