getCollectionItem method

Future<CollectionItem?> getCollectionItem({
  1. required PeerId ownerPeerId,
  2. required String path,
  3. required String key,
  4. PeerId? fromServer,
})

Get a single collection item by key

Implementation

Future<CollectionItem?> getCollectionItem({
  required PeerId ownerPeerId,
  required String path,
  required String key,
  PeerId? fromServer,
}) async {
  final serverId = fromServer ?? await _serverSelector.selectServer(config.preferredServers);
  if (serverId == null) {
    _logger.warning('No S&F server available for collection item retrieval');
    return null;
  }

  try {
    final context = Context();
    final stream = await host.newStream(
      serverId,
      [CollectionHandler.protocolId],
      context,
    ).timeout(config.connectionTimeout);

    final response = await CollectionHandler.getCollectionItem(
      stream,
      ownerPeerId: ownerPeerId,
      path: path,
      key: key,
    ).timeout(config.messageTimeout);

    await stream.close();

    if (!response.isSuccess) {
      _logger.warning('GET collection item $path/$key: ${response.status}');
      return null;
    }

    final content = response.body != null
        ? jsonDecode(utf8.decode(response.body!)) as Map<String, dynamic>
        : <String, dynamic>{};

    return CollectionItem(
      key: key,
      content: content,
      contentHash: response.etag ?? '',
      version: response.version ?? 1,
      createdAt: response.headers['Created-At'] as int? ?? 0,
      updatedAt: response.headers['Updated-At'] as int? ?? 0,
    );
  } on TimeoutException {
    _logger.warning('GET collection item timed out');
    return null;
  } catch (e) {
    _logger.warning('Failed to GET collection item: $e');
    return null;
  }
}