import Bitswap from "ipfs-bitswap" ; import { CID } from "multiformats/basics.js" ; import Old from "cids" ; import { BlockStore , Block } from "./blockstore" ; /**
 * BlockService is a content-addressable store for adding, deleting, and retrieving blocks of immutable data.
 * A block service is backed by a block store as its datastore for blocks, and uses an "exchange" (Bitswap) to fetch
 * blocks from the network. This implementation is a simplified variant of the official IPFS block service, requiring
 * only a simple block store (not a full IPFS repo), and reference to a Bitswap exchange.
 *
 * It satisfies the default IPFS block service interface: https://github.com/ipfs/js-ipfs-block-service.
 */ export class BlockService { param { BlockStore } store param { Bitswap } exchange constructor ( public store , public exchange ? ) { } /**
     * online returns whether the block service is online or not. i.e. does it have a valid exchange?
     */ online ( ) { return this . exchange != null ; } param { Block } block async put ( block ) { if ( this . exchange != null ) { return this . exchange . put ( block ) ; } else { return this . store . put ( block ) ; } } param { Iterable < Block > } blocks async putMany ( blocks ) { if ( this . exchange != null ) { return this . exchange . putMany ( blocks ) ; } else { return this . store . putMany ( blocks ) ; } } param { CID } cid async get ( cid ) { if ( this . exchange != null ) { return this . exchange . get ( new Old ( Buffer . from ( cid . buffer ) ) ) ; } else { return this . store . get ( cid ) ; } } param { Iterable < CID > } cids async * getMany ( cids ) { if ( this . exchange != null ) { const olds = [ ... cids ] . map ( ( cid ) => new Old ( Buffer . from ( cid . buffer ) ) ) ; return this . exchange . getMany ( olds ) ; } else { for ( const cid of cids ) { yield this . store . get ( cid ) ; } } } param { CID } cid async delete ( cid ) { await this . store . delete ( cid ) ; return cid ; } }