Created
December 4, 2019 09:07
-
-
Save antoine-morvan/0b0505147771c492e25a90f88ca4ea40 to your computer and use it in GitHub Desktop.
Run a RDF store with SPARQL engine and HTTP endpoint server frolm Nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as axios from "axios"; | |
import memdown from "memdown"; | |
const quadstore = require("quadstore"); | |
const SparqlEngine = require("quadstore-sparql"); | |
const HttpServer = require("quadstore-http"); | |
(async function() { | |
const db = memdown(); | |
const listenURL = "http://127.0.0.1:8080"; | |
const serverOpts = { contextKey: "http://example.com" }; // Name of fourth term | |
const rdfStore = new quadstore.RdfStore(db, serverOpts); | |
const quads = [ | |
{ | |
subject: { | |
termType: "NamedNode", | |
value: "http://example.com/person#Me" | |
}, | |
predicate: { | |
termType: "NamedNode", | |
value: "http://example.com/properties#age" | |
}, | |
object: { | |
termType: "Literal", | |
value: "42", | |
datatype: { | |
value: "http://www.w3.org/2001/XMLSchema#numeric" | |
} | |
}, | |
graph: { | |
termType: "NamedNode", | |
value: serverOpts.contextKey | |
} | |
} | |
]; | |
rdfStore.put(quads, (putErr: any) => { | |
if (putErr) { | |
console.log(putErr); | |
} | |
}); // callback | |
const sparqlEngine = new SparqlEngine(rdfStore); | |
const opts = { | |
baseUrl: listenURL | |
}; | |
const server = new HttpServer(rdfStore, sparqlEngine, opts); | |
server.listen(8080, "127.0.0.1", (err: any) => { | |
if (err) throw err; | |
}); | |
const endpointURL = listenURL + "/sparql"; | |
const query = `SELECT ?a ?b ?c FROM <${serverOpts.contextKey}> WHERE { ?a ?b ?c. }`; | |
const encodedQuery = "query=" + encodeURIComponent(query); | |
console.log("listengin 2"); | |
try { | |
const instance = axios.default.create(); | |
const completeUrl = endpointURL + "?" + encodedQuery; | |
let requestConfig: axios.AxiosRequestConfig = { | |
url: completeUrl, | |
timeout: 0, | |
method: "GET", | |
headers: { | |
"Accept": "application/sparql-results+json", | |
"Content-Type": "application/x-www-form-urlencoded" | |
} | |
}; | |
const promise = instance.request(requestConfig).then(response => { | |
return response; | |
}); | |
const response = await promise; | |
console.log(response.data.results.bindings); | |
} finally { | |
server.stop(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment