UNPKG

hyperpubee

Version:

Self-publishing over the decentralised internet

120 lines (91 loc) 2.84 kB
const { Pubee } = require('../core/pubee') const hexlexi = require('../core/hexlexi') const { CONTENT, STRUCTURE, ROOT, EMBEDDING, METADATA, LINK } = require('../core/constants') const { getAbsoluteKey } = require('../core/utils') const { validateEmbedding } = require('../core/embedding') const { validateLink } = require('../core/link') class PubeeBuilder { #contentGenerator #structGenerators #embeddingGenerator #linkGenerator #bee constructor (bee) { if (bee.feed.length !== 0) { throw new Error('Cannot init a pubeebuilder with a non-empty bee') } this.#bee = bee this.#contentGenerator = hexlexi.generator() this.#structGenerators = {} this.#embeddingGenerator = hexlexi.generator() this.#linkGenerator = hexlexi.generator() } async addContent (content) { if (content.length === 0) { throw new Error('Cannot add an empty content.') } const key = getAbsoluteKey(CONTENT, this.#contentGenerator.next().value) await this.#bee.put(key, content) return key } async #addChildrenToStructure (key, children) { if (children.length === 0) { throw new Error('Cannot add an empty structure.') } await this.#bee.put(key, children) } #getStructGeneratorOf (name) { if (this.#structGenerators[name] === undefined) { this.#structGenerators[name] = hexlexi.generator() } return this.#structGenerators[name] } async addStructure (name, children) { if (!name) { throw new Error('Cannot add a structure without name.') } const generator = this.#getStructGeneratorOf(name) const key = getAbsoluteKey(STRUCTURE, name, generator.next().value) await this.#addChildrenToStructure(key, children) return key } async addEmbedding (embedding) { validateEmbedding(embedding) const key = getAbsoluteKey( EMBEDDING, this.#embeddingGenerator.next().value ) await this.#bee.put(key, embedding) return key } async addLink (link) { validateLink(link) const key = getAbsoluteKey( LINK, this.#linkGenerator.next().value ) await this.#bee.put(key, link) return key } async addRoot (children) { const key = getAbsoluteKey(STRUCTURE, ROOT) const existingRootContent = await this.#bee.get(key) if (existingRootContent !== null) { throw new Error('Cannot add the root more than once.') } await this.#addChildrenToStructure(key, children) return key } async addMetadata (metadata) { if ((await this.#bee.get(METADATA)) !== null) { throw new Error('Metadata can only be added once') } await this.#bee.put(METADATA, metadata) } async build () { const res = new Pubee(this.#bee) await res.ensureIsValid() return res } } module.exports = PubeeBuilder