UNPKG

alcaeus

Version:

Hydra Core hypermedia-aware client library

54 lines (53 loc) 1.92 kB
import { rdf, hydra } from '@tpluscode/rdf-ns-builders'; export default class { constructor(graph, env, rootResource) { this.env = env; this.__graph = graph; this.__factory = env.rdfine().factory; this.rootNode = graph.node(rootResource); this.__uniqueResources = (() => { let map; return () => { if (!map) { map = this.__graph.in().toArray() .reduce((uniq, pointer) => { if (!uniq.has(pointer.term)) { return uniq.set(pointer.term, this._createEntity(pointer)); } return uniq; }, env.termMap()); } return map; }; })(); } get(uri, { allObjects = false } = {}) { const pointer = this.__graph.namedNode(decodeURI(uri)); const isSubject = pointer.out().terms.length > 0; const isObjectAndAllowedToReturn = allObjects && pointer.in().terms.length; if (!isSubject && !isObjectAndAllowedToReturn) { return undefined; } return this.__factory.createEntity(pointer); } get root() { const collectionNode = this.rootNode.in(hydra.view); if (collectionNode.term) { return this.__factory.createEntity(collectionNode); } return this.__factory.createEntity(this.rootNode); } get length() { return this.__uniqueResources().size; } ofType(classId) { const type = typeof classId === 'string' ? this.env.namedNode(classId) : classId; return this.__graph.has(rdf.type, type).map(r => this._createEntity(r)); } [Symbol.iterator]() { return this.__uniqueResources().values(); } _createEntity(node) { return this.__factory.createEntity(node); } }