generated from jeswr/template-typescript
-
Notifications
You must be signed in to change notification settings - Fork 5
/
n3Writer.temp.ts
64 lines (54 loc) · 1.84 KB
/
n3Writer.temp.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// This is a workaround for https://github.com/rdfjs/N3.js/issues/316
import { Quad, Term } from '@rdfjs/types';
import { DataFactory as DF, Store, Writer } from 'n3';
function isQuoted(term: Term, store: Store) {
return term.termType === 'BlankNode' && store.getQuads(null, null, null, term).length > 0;
}
export class N3Writer {
private _writer: any = new Writer();
_encodePredicate(term: Term): string {
if (term.termType === 'NamedNode') {
switch (term.value) {
case 'http://www.w3.org/2000/10/swap/log#implies':
return '=>';
case 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type':
return 'a'
}
}
return this._writer._encodeIriOrBlank(term);
}
_encodeSubject(entity: Term, store: Store): string {
if (isQuoted(entity, store)) {
return `{${this.quadsStoreToString(store, entity)}}`
}
return this._writer._encodeSubject(entity)
}
_encodeObject(entity: Term, store: Store): string {
if (isQuoted(entity, store)) {
return `{${this.quadsStoreToString(store, entity)}}`
}
return this._writer._encodeObject(entity)
}
// ### `quadToString` serializes a quad as a string
quadToString(t: Quad, store: Store): string {
return `${
this._encodeSubject(t.subject, store)
} ${
this._encodePredicate(t.predicate as any)
} ${
this._encodeObject(t.object, store)
}`;
}
// ### `quadsToString` serializes an array of quads as a string
quadsStoreToString(store: Store, graph: Term = DF.defaultGraph()): string {
return store.getQuads(null, null, null, graph)
.map(t => this.quadToString(t, store))
.join(' . ') + ' . ';
}
quadsToString(quads: Quad[]): string {
return this.quadsStoreToString(new Store(quads))
}
}
export function write(quads: Quad[]) {
return (new N3Writer).quadsToString(quads);
}