Last active
March 23, 2022 20:10
-
-
Save pawelsa/0fdda2e3d6b902ed3ee298ab93081540 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Api { | |
static const baseUrl = "https://api.themoviedb.org/3/movie/"; | |
Future<Response> get({ | |
required Uri uri, | |
required Response Function(String body) mapper, | |
Map<String, String>? headers, | |
}) { | |
uri = _prepareUri(uri); | |
return http.get(uri, headers: headers).then( | |
(response) => _handleResponse(response, mapper), | |
onError: _handleOnError, | |
); | |
} | |
ErrorResponse _handleOnError(e) { | |
if(e is SocketException){ | |
return NoInternetResponse(); | |
} else if (e is TimeoutException){ | |
return TimeoutResponse(); | |
} | |
return GeneralErrorResponse(); | |
} | |
Uri _prepareUri(Uri uri) { | |
final newQueryParameters = Map<String, dynamic>.from(uri.queryParameters); | |
newQueryParameters["api_key"] = Secret.apiKey; | |
uri = uri.replace(queryParameters: newQueryParameters); | |
return uri; | |
} | |
Response _handleResponse(http.Response response, Response Function(String body) mapper) { | |
switch (response.statusCode) { | |
case 200: | |
return mapper(response.body); | |
case 400: | |
return BadRequestResponse(); | |
case 401: | |
case 403: | |
return UnAuthorizedResponse(); | |
case 404: | |
return NotFoundResponse(); | |
// other errors we want to handle | |
default: | |
return NotHandledResponse(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NotHandledResponse extends ErrorResponse {} | |
class BadRequestResponse extends ErrorResponse {} | |
class UnAuthorizedResponse extends ErrorResponse {} | |
class NotFoundResponse extends ErrorResponse {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment