Skip to content

Commit 0ebe0d4

Browse files
committed
Address PR feedback: Use pattern matching in StsAuthClient
1 parent a83d1a4 commit 0ebe0d4

File tree

1 file changed

+27
-22
lines changed

1 file changed

+27
-22
lines changed

googleapis_auth/lib/src/sts_auth_client.dart

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -117,37 +117,42 @@ class StsAuthClient extends AutoRefreshDelegatingClient {
117117
}
118118

119119
Future<String> _getSubjectToken() async {
120-
if (_credentialSource.containsKey('file')) {
121-
final fileField = _credentialSource['file'] as String;
122-
return await File(fileField).readAsString();
123-
} else if (_credentialSource.containsKey('url')) {
124-
final url = _credentialSource['url'] as String;
125-
final headers = _credentialSource['headers'] as Map<String, dynamic>?;
126-
final format = _credentialSource['format'] as Map<String, dynamic>?;
127-
128-
final parsedHeaders = headers?.map(
129-
(key, value) => MapEntry(key, value.toString()),
130-
);
131-
132-
final response = await baseClient.get(
133-
Uri.parse(url),
134-
headers: parsedHeaders,
135-
);
120+
final source = _credentialSource;
121+
if (source case {'file': final String file}) {
122+
return await File(file).readAsString();
123+
} else if (source case {'url': final String url}) {
124+
final headers = switch (source['headers']) {
125+
final Map<String, dynamic> h => h.map(
126+
(key, value) => MapEntry(key, value.toString()),
127+
),
128+
_ => null,
129+
};
130+
131+
final response = await baseClient.get(Uri.parse(url), headers: headers);
136132

137133
if (response.statusCode != 200) {
138-
throw Exception(
134+
throw ServerRequestFailedException(
139135
'Failed to retrieve subject token from URL: $url. '
140-
'Status code: ${response.statusCode}, Body: ${response.body}',
136+
'Status code: ${response.statusCode}',
137+
responseContent: response.body,
138+
statusCode: response.statusCode,
141139
);
142140
}
143141

144142
var token = response.body;
145143

146-
if (format != null && format['type'] == 'json') {
144+
if (source['format'] case {
145+
'type': 'json',
146+
'subject_token_field_name': final String fieldName,
147+
}) {
147148
final json = jsonDecode(token) as Map<String, dynamic>;
148-
final subjectTokenFieldName =
149-
format['subject_token_field_name'] as String;
150-
token = json[subjectTokenFieldName] as String;
149+
if (json[fieldName] case final String subjectToken) {
150+
token = subjectToken;
151+
} else {
152+
throw ArgumentError(
153+
'Subject token field "$fieldName" not found in JSON response.',
154+
);
155+
}
151156
}
152157
return token;
153158
}

0 commit comments

Comments
 (0)