dataRefFromString function

DataRefModel? dataRefFromString(
  1. String? input
)

Creates a DataRefModel from a given path string. If the path ends with a '/', it represents a collection path, otherwise, it represents a document path.

Implementation

DataRefModel? dataRefFromString(String? input) {
  if (input == null) {
    return null;
  }

  final segments = input.split('/').where((e) => e.isNotEmpty).toList();

  if (segments.isEmpty) {
    throw ArgumentError('[dataRefFromString] Input cannot be an empty path.');
  }

  final endsWithSlash = input.endsWith('/');

  final isCollectionPath = endsWithSlash && segments.length.isOdd;
  final isDocumentPath = !endsWithSlash && segments.length.isEven;

  if (!isCollectionPath && !isDocumentPath) {
    throw ArgumentError(
      '[dataRefFromString] Invalid path: Path must end with "/" for collection paths, or not end with "/" for document paths.',
    );
  }

  // The last segment is the ID if it's a document path.
  final id = isDocumentPath ? segments.removeLast() : null;

  return DataRefModel(
    id: id,
    collection: segments,
  );
}