Skip to content

Commit

Permalink
Support base IRIs in writer.
Browse files Browse the repository at this point in the history
Closes #157
  • Loading branch information
RubenVerborgh committed Jan 14, 2021
1 parent 4e91075 commit 07b0f35
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/N3Writer.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export default class N3Writer {
if (!(/triple|quad/i).test(options.format)) {
this._lineMode = false;
this._graph = DEFAULTGRAPH;
this._baseIRI = options.baseIRI;
this._prefixIRIs = Object.create(null);
options.prefixes && this.addPrefixes(options.prefixes);
}
Expand Down Expand Up @@ -145,8 +146,11 @@ export default class N3Writer {
entity = this.list(this._lists[entity.value]);
return 'id' in entity ? entity.id : `_:${entity.value}`;
}
// Escape special characters
let iri = entity.value;
// Use relative IRIs if requested and possible
if (this._baseIRI && iri.startsWith(this._baseIRI))
iri = iri.substr(this._baseIRI.length);
// Escape special characters
if (escape.test(iri))
iri = iri.replace(escapeAll, characterReplacer);
// Try to represent the IRI as prefixed name
Expand Down
12 changes: 12 additions & 0 deletions test/N3Writer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,18 @@ describe('Writer', () => {
});
});

it('uses a base IRI when given', done => {
const writer = new Writer({ baseIRI: 'http://example.org/foo/' });
writer.addQuad(new Quad(
new NamedNode('http://example.org/foo/'),
new NamedNode('http://example.org/foo/#b'),
new NamedNode('http://example.org/foo/cdeFgh/ijk')));
writer.end((error, output) => {
output.should.equal('<> <#b> <cdeFgh/ijk>.\n');
done(error);
});
});

it('should accept triples with separated components', done => {
const writer = new Writer();
writer.addQuad(new NamedNode('a'), new NamedNode('b'), new NamedNode('c'));
Expand Down

0 comments on commit 07b0f35

Please sign in to comment.