UNPKG

dweb-loader

Version:

JSON-LD document loader for IPFS and IPLD URIs

38 lines (32 loc) 936 B
const CID = require("cids") async function ipldLoader(ipfs, path, documentUrl) { const cid = new CID(path) if (cid.codec === "dag-cbor") { const { value } = await ipfs.dag.get(path) return { document: value, documentUrl } } else { throw new Error("Unsupported IPLD codec") } } async function ipfsLoader(ipfs, path, documentUrl) { let doc = "" for await (const chunk of ipfs.cat(path)) { doc += chunk.toString() } return { document: JSON.parse(doc), documentUrl } } const documentLoaders = { "ipld://": ipldLoader, "dweb:/ipld/": ipldLoader, "ipfs://": ipfsLoader, "dweb:/ipfs/": ipfsLoader, } const prefixes = Object.keys(documentLoaders) module.exports = (ipfs) => async (url, options) => { const prefix = prefixes.find((prefix) => url.indexOf(prefix) === 0) if (prefix) { return documentLoaders[prefix](ipfs, url.slice(prefix.length), url) } else { throw new Error("Could not load document", url) } }