@tpluscode/sparql-builder
Version:
Simple JS library to build SPARQL queries
28 lines (27 loc) • 949 B
JavaScript
import { sparql } from '@tpluscode/rdf-string';
import RDF from '@rdfjs/data-model';
function toSingleLine(line, value) {
return sparql `${line} ${value}`;
}
export function VALUES(...values) {
if (values.length === 0) {
return '';
}
const variables = [...new Set(values.map(Object.keys).flat())].map(RDF.variable);
const vectors = values.reduce((previous, current) => {
const vector = variables.map((variable) => {
const value = current[variable.value];
if (value === null || typeof value === 'undefined') {
return 'UNDEF';
}
if (typeof value === 'string') {
return RDF.literal(value);
}
return value;
});
return sparql `${previous}\n(${vector.reduce(toSingleLine, sparql ``)} )`;
}, sparql ``);
return sparql `VALUES (${variables.reduce(toSingleLine, sparql ``)} )
{${vectors}
}`;
}