Created
March 21, 2022 06:51
-
-
Save dev4jam/299108a5b506ac3837d1447804b39764 to your computer and use it in GitHub Desktop.
Final network service
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 NetworkService { | |
NetworkService({ | |
required this.baseUrl, | |
dioClient, | |
httpHeaders, | |
}) : this._dio = dioClient, | |
this._headers = httpHeaders ?? {}; | |
Dio? _dio; | |
final String baseUrl; | |
Map<String, String> _headers; | |
Future<Dio> _getDefaultDioClient() async { | |
_headers['content-type'] = 'application/json; charset=utf-8'; | |
final dio = Dio() | |
..options.baseUrl = baseUrl | |
..options.headers = _headers | |
..options.connectTimeout = 5000 // 5 seconds | |
..options.receiveTimeout = 3000; // 3 seconds | |
} | |
return dio; | |
} | |
void addBasicAuth(String accessToken) { | |
_headers['Authorization'] = 'Bearer $accessToken'; | |
} | |
Future<NetworkResponse<Model>> execute<Model>( | |
NetworkRequest request, | |
Model Function(Map<String, dynamic>) parser, { | |
ProgressCallback? onSendProgress = null, | |
ProgressCallback? onReceiveProgress = null, | |
}) async { | |
if (_dio == null) { | |
_dio = await _getDefaultDioClient(); | |
} | |
final req = _PreparedNetworkRequest<Model>( | |
request, | |
parser, | |
_dio!, | |
{..._headers, ...(request.headers ?? {})}, | |
onSendProgress, | |
onReceiveProgress, | |
); | |
final result = await compute( | |
executeRequest<Model>, | |
req, | |
); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment