Created
May 2, 2019 06:04
-
-
Save iampawan/67a5711a9d3d8b1533382763e16026bd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import 'dart:async'; | |
import 'dart:convert'; | |
import 'dart:io'; | |
import 'package:flutter/foundation.dart'; | |
import 'package:http/http.dart' as http; | |
import 'package:qart/services/network_service_response.dart'; | |
class RestClient { | |
Map<String, String> authHeaders; | |
Map<String, String> headers = { | |
HttpHeaders.contentTypeHeader: 'application/json', | |
HttpHeaders.acceptHeader: 'application/json', | |
}; | |
RestClient() { | |
authHeaders = { | |
HttpHeaders.contentTypeHeader: 'application/json', | |
HttpHeaders.acceptHeader: 'application/json', | |
}; | |
} | |
Future<MappedNetworkServiceResponse<T>> getAsync<T>(String resourcePath, | |
{bool customHeaders}) async { | |
var response = await http.get( | |
resourcePath, | |
headers: customHeaders == true ? authHeaders : headers, | |
); | |
return await processResponse<T>(response); | |
} | |
Future<MappedNetworkServiceResponse<T>> postAsync<T>( | |
String resourcePath, dynamic data, | |
{bool customHeaders}) async { | |
var content = json.encoder.convert(data); | |
// print(content); | |
var response = await http.post(resourcePath, | |
body: content, headers: customHeaders == true ? authHeaders : headers); | |
return await processResponse<T>(response); | |
} | |
Future<MappedNetworkServiceResponse<T>> processResponse<T>( | |
http.Response response) async { | |
if (!((response.statusCode < HttpStatus.ok) || | |
(response.statusCode >= HttpStatus.multipleChoices) || | |
(response.body == null))) { | |
var resultClass = await compute(jsonParserIsolate, response.body); | |
return new MappedNetworkServiceResponse<T>( | |
mappedResult: resultClass, | |
networkServiceResponse: new NetworkServiceResponse<T>(success: true)); | |
} else { | |
var errorResponse = response.body; | |
return new MappedNetworkServiceResponse<T>( | |
networkServiceResponse: new NetworkServiceResponse<T>( | |
success: false, | |
message: "(${response.statusCode}) ${errorResponse.toString()}")); | |
} | |
} | |
static Map<String, dynamic> jsonParserIsolate(String res) { | |
return jsonDecode(res); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment