UNPKG

@ceramicnetwork/pinning-aggregation

Version:

Aggregated pinning

62 lines 2.29 kB
import { toString } from 'uint8arrays/to-string'; import * as sha256 from '@stablelib/sha256'; export class UnknownPinningService extends Error { constructor(designator) { super(`Unknown pinning service ${designator}`); } } const textEncoder = new TextEncoder(); function uniq(input) { return [...new Set(input)]; } export class PinningAggregation { constructor(backends) { this.backends = backends; const allIds = this.backends.map((b) => b.id).join('\n'); const bytes = textEncoder.encode(allIds); const digest = toString(sha256.hash(bytes), 'base64urlpad'); this.id = `pinning-aggregation@${digest}`; } static build(ipfs, connectionStrings, pinners = []) { const backends = connectionStrings.map((s) => { const protocol = s.match(`://`) ? new URL(s).protocol.replace(':', '') : s; const match = protocol.match(/^(\w+)\+?/); const designator = match ? match[1] : ''; const found = pinners.find((pinner) => pinner.designator === designator); if (found) { return new found(s, ipfs); } else { throw new UnknownPinningService(designator); } }); return new PinningAggregation(backends); } open() { this.backends.forEach((service) => service.open()); } async close() { await Promise.all(this.backends.map(async (service) => service.close())); } async pin(cid) { await Promise.all(this.backends.map(async (service) => service.pin(cid))); } async unpin(cid) { Promise.all(this.backends.map(async (service) => service.unpin(cid))).catch(() => { }); } async ls() { const perBackend = await Promise.all(this.backends.map((b) => b.ls())); const allCids = uniq(perBackend.flatMap((p) => Object.keys(p))); const result = {}; allCids.forEach((cid) => { result[cid] = perBackend.flatMap((p) => p[cid]).filter(Boolean); }); return result; } async info() { const perBackend = await Promise.all(this.backends.map((b) => b.info())); return Object.assign({}, ...perBackend); } } //# sourceMappingURL=index.js.map