refFromUrl method

DatabaseReference refFromUrl(
  1. String url
)

The reference for a full url of this database (for example https://my-project-default-rtdb.firebaseio.com/a/b). Path segments are percent-decoded.

Outside an emulator the URL without its path must be accepted by the constructor's databaseUrl rules and name this database: its host, and its namespace (?ns= or the first label of a firebaseio.com / firebasedatabase.app host). With an emulator the host and port are not compared, but the URL must still be http, https, ws or wss with a valid host, no user info and no query key but ns, and a namespace it names (the same two ways) must be this database's. Anything else throws an ArgumentError, as does a path that is not valid percent-encoded UTF-8 or that ref refuses.

No message quotes the whole URL, its user info or its query. A message may name the URL's host (another host) and, as ref does, a decoded path it refuses.

Implementation

DatabaseReference refFromUrl(String url) {
  final ({String root, String path}) parts = _splitPath(url);
  final RepoInfo here = _target.info;
  final String? namespace;
  if (here.isUsingEmulator) {
    namespace = _Target._argument('url', () => namespaceOfUrl(parts.root));
  } else {
    final RepoInfo info = _Target._argument(
      'url',
      () => parseDatabaseUrl(parts.root),
    );
    if (info.host != here.host) {
      throw ArgumentError(
        'refFromUrl: Host name does not match the current database: '
            '(found ${info.host} but expected ${here.host})',
        'url',
      );
    }
    namespace = info.namespace;
  }
  if (namespace != null && namespace != here.namespace) {
    // The URL's ns is not quoted: it is a query value.
    throw ArgumentError(
      'refFromUrl: The URL names another database than this one '
          '(this namespace is ${here.namespace})',
      'url',
    );
  }
  return ref(parts.path);
}