From 740e30ff7624aa07cf5949615c1b17b7a2ebe27d Mon Sep 17 00:00:00 2001 From: Alvin Sebastian Date: Tue, 21 May 2024 12:10:52 +0000 Subject: [PATCH] Improve addTermDefinition method to handle edge cases --- lib/rocrate.js | 10 ++++++++++ package.json | 2 +- test/rocrate.new.spec.js | 10 +++++++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/rocrate.js b/lib/rocrate.js index b9f844a..a6600ff 100644 --- a/lib/rocrate.js +++ b/lib/rocrate.js @@ -356,8 +356,18 @@ class ROCrate { } } + /** + * Add the term and its definition to the first context definition (a map) found from the `@context` entries. + * If no existing context definition found, a new one will be created. + * @param {string} term + * @param {string|object} definition + */ addTermDefinition(term, definition) { var context = Array.from(this.__context).find(c => typeof c === 'object'); + if (!context) { + context = {}; + this.__context.add(context); + } context[term] = definition; const id = typeof definition === 'string' ? definition : definition["@id"] || term; this.__contextTermIndex.set(term, definition); diff --git a/package.json b/package.json index 5b26dd7..931dbb3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ro-crate", - "version": "3.3.7", + "version": "3.3.8", "description": "Research Object Crate (RO-Crate) utilities for making and consuming crates", "main": "index.js", "scripts": { diff --git a/test/rocrate.new.spec.js b/test/rocrate.new.spec.js index 0fa2824..1eb79dd 100644 --- a/test/rocrate.new.spec.js +++ b/test/rocrate.new.spec.js @@ -687,7 +687,15 @@ describe("addTermDefinition", function () { assert.ok(!crate.getDefinition('Geometry')); crate.addTermDefinition('Geometry', 'http://www.opengis.net/ont/geosparql#Geometry'); assert.ok(crate.getDefinition('Geometry')); - + }); + it("can add a new term to new context", async function () { + const crate = new ROCrate({'@context': 'http://example.com/test'}, {array: true}); + //await crate.resolveContext(); + assert.ok(!crate.getDefinition('Geometry')); + crate.addTermDefinition('Geometry', 'http://www.opengis.net/ont/geosparql#Geometry'); + assert.equal(crate.getDefinition('Geometry')['@id'], 'http://www.opengis.net/ont/geosparql#Geometry'); + assert.equal(crate.getTerm('http://www.opengis.net/ont/geosparql#Geometry'), 'Geometry'); + assert.equal(crate.context.length, 2); }); }); describe("getTerm", function () {