createCollection method

Future<CollectionInfo?> createCollection({
  1. required String path,
  2. required String name,
  3. CollectionVisibility? visibility,
  4. PeerId? toServer,
})

Create a new collection on your store.

Without a visibility the server makes the collection private: only you can read it.

Implementation

Future<CollectionInfo?> createCollection({
  required String path,
  required String name,
  CollectionVisibility? visibility,
  PeerId? toServer,
}) async {
  final serverId = toServer ?? await _serverSelector.selectServer(config.preferredServers);
  if (serverId == null) {
    _logger.warning('No S&F server available for collection creation');
    return null;
  }

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

    final response = await CollectionHandler.createCollection(
      stream,
      ownerPeerId: host.id,
      path: path,
      name: name,
      visibility: visibility,
    ).timeout(config.messageTimeout);

    await stream.close();

    if (!response.isSuccess) {
      _logger.warning('CREATE collection $path: ${response.status} ${response.error}');
      return null;
    }

    final body = jsonDecode(utf8.decode(response.body!)) as Map<String, dynamic>;
    return CollectionInfo(
      path: body['path'] as String,
      name: body['name'] as String,
      recordCount: body['recordCount'] as int? ?? 0,
      createdAt: body['createdAt'] as int? ?? DateTime.now().millisecondsSinceEpoch,
    );
  } on TimeoutException {
    _logger.warning('CREATE collection timed out');
    return null;
  } catch (e) {
    _logger.warning('Failed to CREATE collection: $e');
    return null;
  }
}