create method

Future<T> create(
  1. Map<String, Object?> data, {
  2. String? optimisticId,
  3. String? queryKey,
  4. Object position = 'start',
})

Create an entity and optionally expose an optimistic placeholder.

Implementation

Future<T> create(
  Map<String, Object?> data, {
  String? optimisticId,
  String? queryKey,
  Object position = 'start',
}) async {
  final graph = ref.read(entityGraphProvider);
  if (optimisticId != null) {
    if (graph.readCanonicalEntity(type, optimisticId) != null) {
      throw TerminalError(
        'Optimistic id $type/$optimisticId already exists in the graph',
      );
    }
    graph.upsertEntity(type, optimisticId, data);
    graph.markEntityOptimistic(type, optimisticId);
    if (queryKey != null) {
      graph.insertIdInList(
        queryKey,
        optimisticId,
        position,
        entityType: type,
      );
    }
  }
  state = const EntityMutationState(isMutating: true);
  try {
    final transport = ref.read(entityTransportRegistryProvider).get<T>(type);
    final row = await transport.create(data);
    final confirmedId = transport.identify(row);
    if (optimisticId != null && optimisticId != confirmedId) {
      graph.removeEntity(type, optimisticId);
    }
    graph.upsertEntity(
      type,
      confirmedId,
      entityToGraphRow(row, toGraph ?? transport.toGraph),
    );
    graph.markEntitySynced(type, confirmedId);
    if (queryKey != null) {
      graph.insertIdInList(queryKey, confirmedId, position, entityType: type);
    }
    graph.invalidateListsForType(type);
    state = EntityMutationState(value: row);
    return row;
  } on Object catch (error) {
    final typed = toEntityGraphError(error);
    if (optimisticId != null) graph.removeEntity(type, optimisticId);
    state = EntityMutationState(error: typed);
    throw typed;
  }
}