Skip to content

Commit

Permalink
Add method to check for duplicates before creating local name
Browse files Browse the repository at this point in the history
  • Loading branch information
adzialocha authored and sandreae committed Jun 3, 2024
1 parent e7022a4 commit 8e5a6da
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions packages/app/lib/models/local_names.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:gql/ast.dart';
import 'package:graphql/client.dart';
import 'package:p2panda/p2panda.dart';

import 'package:app/io/graphql/graphql.dart';
import 'package:app/io/p2panda/publish.dart';
import 'package:app/models/base.dart';
import 'package:app/models/schema_ids.dart';
Expand Down Expand Up @@ -53,15 +54,16 @@ String get localNameFields {
''';
}

String searchLocalNamesQuery(String query) {
String searchLocalNamesQuery(String query, {bool strict = false}) {
const schemaId = SchemaIds.bee_local_name;
final op = strict ? "eq" : "contains";

return '''
query SearchLocalNames {
$DEFAULT_RESULTS_KEY: all_$schemaId(
first: 5,
filter: {
name: { contains: "$query" },
name: { $op: "$query" },
},
orderBy: "name",
orderDirection: ASC,
Expand All @@ -74,6 +76,24 @@ String searchLocalNamesQuery(String query) {
''';
}

/// Safely create a new local name instance if we're not aware yet of one with
/// the same "name" value.
Future<LocalName> createDeduplicatedLocalName(String name) async {
final response = await client.query(
QueryOptions(document: gql(searchLocalNamesQuery(name, strict: true))));

if (!response.hasException) {
final documents =
response.data![DEFAULT_RESULTS_KEY]['documents'] as List<dynamic>;

if (documents.isNotEmpty) {
return LocalName.fromJson(documents[0] as Map<String, dynamic>);
}
}

return await LocalName.create(name: name);
}

Future<DocumentViewId> createLocalName({required String name}) async {
List<(String, OperationValue)> fields = [
("name", OperationValue.string(name)),
Expand Down

0 comments on commit 8e5a6da

Please sign in to comment.