sparnatural
Version:
Visual client-side SPARQL query builder and knowledge graph exploration tool
74 lines • 2.82 kB
JavaScript
import { QueryEngine } from '@comunica/query-sparql-rdfjs-lite';
/**
* A SPARQL handler that executes queries against an in-memory RDF store,
* and returns results in SPARQL JSON format.
*/
export class StoreBasedSparqlHandler {
constructor(store) {
this.store = store;
this.engine = new QueryEngine();
}
executeSparql(sparql, callback, errorCallback) {
// Wrap the async execution in a Promise
(async () => {
try {
const bindingsStream = await this.engine.queryBindings(sparql, {
sources: [this.store]
});
var results = {
head: {
vars: []
},
results: {
bindings: []
}
};
let first = true;
// serialize results into SPARQL JSON format
bindingsStream.on('data', (binding) => {
// Convert each binding to a JSON object
const result = {};
binding.forEach((value, key) => {
// console.log(`Key: ${key.value}, Value: ${value.value}, Type: ${this.getJsonType(value.termType)}`);
result[key.value] = {
value: value.value,
type: this.getJsonType(value.termType)
};
// cheating : we read the first binding to read variables
if (first) {
results.head.vars.push(key.value);
}
first = false;
});
results.results.bindings.push(result);
});
bindingsStream.on('end', () => {
// The data-listener will not be called anymore once we get here.
console.log(JSON.stringify(results, null, 2));
callback(results);
});
bindingsStream.on('error', (error) => {
console.error(error);
});
}
catch (error) {
console.error('Error executing SPARQL query:', error);
if (errorCallback) {
errorCallback(error);
}
else {
throw error;
}
}
})();
}
getJsonType(termType) {
switch (termType) {
case 'NamedNode': return 'uri';
case 'BlankNode': return 'bnode';
case 'Literal': return 'literal';
default: return termType.toLowerCase();
}
}
}
//# sourceMappingURL=StoreBasedSparqlHandler.js.map