queryCollection method
Query a collection with JSONB filtering
Implementation
Future<CollectionQueryResult?> queryCollection({
required PeerId ownerPeerId,
required String path,
Map<String, dynamic>? filter,
String? sortField,
bool? sortAsc,
int? limit,
int? offset,
PeerId? fromServer,
}) async {
final serverId = fromServer ?? await _serverSelector.selectServer(config.preferredServers);
if (serverId == null) {
_logger.warning('No S&F server available for collection query');
return null;
}
try {
final context = Context();
final stream = await host.newStream(
serverId,
[CollectionHandler.protocolId],
context,
).timeout(config.connectionTimeout);
final response = await CollectionHandler.queryCollection(
stream,
ownerPeerId: ownerPeerId,
path: path,
filter: filter,
sortField: sortField,
sortAsc: sortAsc,
limit: limit,
offset: offset,
).timeout(config.messageTimeout);
await stream.close();
if (!response.isSuccess) {
_logger.warning('QUERY collection $path: ${response.status}');
return null;
}
final body = jsonDecode(utf8.decode(response.body!)) as Map<String, dynamic>;
final itemsList = body['items'] as List<dynamic>? ?? [];
final items = itemsList.map((item) {
final i = item as Map<String, dynamic>;
return CollectionItem(
key: i['key'] as String,
content: i['content'] as Map<String, dynamic>? ?? {},
contentHash: i['hash'] as String? ?? '',
version: i['version'] as int? ?? 1,
createdAt: i['createdAt'] as int? ?? 0,
updatedAt: i['updatedAt'] as int? ?? 0,
);
}).toList();
return CollectionQueryResult(
items: items,
totalCount: response.totalCount ?? items.length,
hasMore: response.hasMore ?? false,
);
} on TimeoutException {
_logger.warning('QUERY collection timed out');
return null;
} catch (e) {
_logger.warning('Failed to QUERY collection: $e');
return null;
}
}