/** * @module Ontology */ export class Ontology { #data; /** * @param {Object} data The parsed ontology object (from JSON) */ set data(data) { this.#data = data; } /** * @param {String} id */ getInstanceById(id) { return this.#data.instancesById[id]; } /** * @todo Revise loop approach... * @param {String} label * @param {String} lang The language identifier, either 'en' or 'it' * @returns {Object} The instance object as per onto JSON... (document it!!) */ getInstanceByLabel(label, lang) { if (!['en','it'].includes(lang)) { throw new Error(`Invalid language string provided: '${lang}'`); } let instance = {}; for (const key of Object.keys(this.#data.instancesById)) { const currentInstance = this.#data.instancesById[key]; const currentLabel = currentInstance.label[lang]; if (currentLabel === label) { instance = currentInstance; break; } } return instance; } /** * @returns {Array<{en: string, it: string}>} The bloody array of label objects */ getInstanceLabels() { const data = this.#data; const instances = []; for (const key of Object.keys(data.instancesById)) { instances.push(data.instancesById[key]?.label); } return instances; } } /** * @todo Temporarily returns domains and ontology labels only * Traverse an ontology from its JSON description * @param {Object} ontologyObject The parsed ontology JSON * @returns {Object} */ export async function traverseOntology(ontologyObject) { //const ontology = await loadOntology(jsonPath); const modules = ontologyObject.domains; const domains = []; for (const module of modules) { let tree = []; for (const classTree of module.classTrees) { traverseClasses(classTree, tree); } domains.push({ id: module.label.it ?? module.label.en, tree }); } return domains; } /** * * @param {Object} ontologyClass * @param {Array} tree * @param {Number} depth */ function traverseClasses(ontologyClass, tree, depth = 1) { const ontologyNode = { id: ontologyClass.id, label: ontologyClass.label, depth, children: [], }; tree.push(ontologyNode); if (ontologyClass.children && Array.isArray(ontologyClass.children)) { for(const child of ontologyClass.children) { ontologyNode.children.push( traverseClasses(child, tree, depth + 1) ); } } } /** * Load an ontology from its JSON description * @param {String} jsonPath The path (URI) of the ontology JSON file * @returns {Object} */ export async function loadOntology(jsonPath) { const ontology = await fetch(jsonPath) .then(res => res.json()) .catch(err => console.error(err)); return ontology; }