-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQueryManager.ts
40 lines (35 loc) · 1.07 KB
/
QueryManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import type { SparqlQuery } from 'sparqljs';
import type { QueryOptions } from 'types/client';
import { sparqlQueryToString } from './sparql/parser';
import { sparqlWithSubstitution } from './sparql/replace';
import { sparql } from './sparql/tag';
export class QueryManager {
#prefixes: Record<string, string>;
constructor({ prefixes }) {
this.#prefixes = prefixes;
}
#getPrefixes(): string {
return Object.entries(this.#prefixes)
.map(([prefix, uri]) => `PREFIX ${prefix}: <${uri}>`)
.join('\n');
}
transform({ query, variables = {} }: QueryOptions): SparqlQuery {
let queryObject;
// parse query string if needed
if (typeof query === 'string') {
queryObject = sparql(`${this.#getPrefixes()}\n${query}`);
} else {
queryObject = query;
}
// apply substitutions
const queryWithVars = sparqlWithSubstitution({
query: queryObject,
variables,
});
return queryWithVars;
}
queryToString(query: SparqlQuery): string {
const queryString = sparqlQueryToString(query);
return queryString;
}
}