getToken method Null safety

  1. @override
Future<AuthToken?> getToken(
  1. AuthServer server,
  2. {String? byAccessToken,
  3. String? byRefreshToken}
)
override

Returns a AuthToken searching by its access token or refresh token.

Exactly one of byAccessToken and byRefreshToken may be non-null, if not, this method must throw an error.

If byAccessToken is not-null and there exists a matching AuthToken.accessToken, return that token. If byRefreshToken is not-null and there exists a matching AuthToken.refreshToken, return that token.

If no match is found, return null.

server is the AuthServer requesting the AuthToken.

Implementation

@override
Future<AuthToken?> getToken(
  AuthServer server, {
  String? byAccessToken,
  String? byRefreshToken,
}) async {
  if (byAccessToken != null && byRefreshToken != null) {
    throw ArgumentError(
      "Exactly one of 'byAccessToken' or 'byRefreshToken' must be non-null.",
    );
  }

  final query = Query<ManagedAuthToken>(context!);
  if (byAccessToken != null) {
    query.where((o) => o.accessToken).equalTo(byAccessToken);
  } else if (byRefreshToken != null) {
    query.where((o) => o.refreshToken).equalTo(byRefreshToken);
  } else {
    throw ArgumentError(
      "Exactly one of 'byAccessToken' or 'byRefreshToken' must be non-null.",
    );
  }

  final token = await query.fetchOne();

  return token?.asToken();
}