putBlock method

  1. @override
Future<AddBlockResponse> putBlock(
  1. Block block
)

Returns a Future that resolves to an AddBlockResponse after storing the given block.

Implementation

@override
/// Returns a [Future] that resolves to an [AddBlockResponse] after storing the given [block].
Future<AddBlockResponse> putBlock(Block block) async {
  try {
    final cidStr = block.cid.toString();
    final blockPath = p.join(path, cidStr);

    // Save to disk first
    final alreadyOnDisk = await getPlatform().exists(blockPath);
    final alreadyIndexed = _blockIndex.contains(cidStr);
    if (!alreadyOnDisk) {
      await getPlatform().writeBytes(blockPath, block.data);
    }

    // Update index and cache
    _blockIndex.add(cidStr);
    _blockCache.put(cidStr, block);
    if (!alreadyIndexed) {
      _totalSize += block.size;
    }

    if (alreadyOnDisk || alreadyIndexed) {
      _logger.debug('Block already exists: $cidStr');
      return BlockResponseFactory.successAdd('Block already exists');
    }

    _logger.debug('Block added successfully: $cidStr');
    return BlockResponseFactory.successAdd('Block added successfully');
  } catch (e) {
    _logger.error('Failed to put block', e);
    return BlockResponseFactory.failureAdd('Failed to put block: $e');
  }
}