From 9fcd2e0a16f3f9de89ae1b7a77ce20a8f42e4b38 Mon Sep 17 00:00:00 2001 From: MohammadTaha Basiri Date: Tue, 4 Jan 2022 16:14:57 +0330 Subject: [PATCH] D1APP-22 request service bug fixed --- lib/services/network/request.dart | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/lib/services/network/request.dart b/lib/services/network/request.dart index 5296878..435a17b 100644 --- a/lib/services/network/request.dart +++ b/lib/services/network/request.dart @@ -4,11 +4,16 @@ import 'dart:io'; import 'package:http/http.dart' as http; class RequestService { - static late String token; + static late String _token; + + static set token(value) => _token = value; + + Map get result => _body['result'] ?? const {}; + Map get errors => _body['errors'] ?? const {}; String? errorMessage; - dynamic body; + dynamic _body; final Map _headers = { "accept": "*/*", "Content-Type": "application/json; charset=UTF-8", @@ -26,7 +31,7 @@ class RequestService { }) { if (body != null) _requestBody = body; if (requestHeaders != null) _headers.addAll(requestHeaders); - if (useAutherization) _headers.addAll({'Authorization': 'Bearer $token'}); + if (useAutherization) _headers.addAll({'Authorization': 'Bearer $_token'}); if (body != null) _requestBody = body; } @@ -61,8 +66,10 @@ class RequestService { const Duration(seconds: 10), ) .catchError( - (e) => throw e, - ); + (e) { + throw e; + }, + ); _handleResponse(response); } catch (e) { _handleError(null); @@ -140,7 +147,7 @@ class RequestService { void _handleResponse(http.Response? response) { if (_handleError(response)) { if (response!.body.isNotEmpty) { - body = json.decode(response.body); + _body = json.decode(response.body); } } } @@ -156,8 +163,16 @@ class RequestService { return false; } if (response.statusCode != 200 && response.statusCode != 204) { + String data; + if (response.body.isEmpty) { + data = 'No results!'; + } else if (response.body.contains('')) { + data = response.body; + } else { + data = jsonDecode(response.body); + } log( - 'Request to [$url] failed with status code ${response.statusCode} & result : \n ${response.body.isNotEmpty ? json.decode(response.body) : 'No result.'}', + 'Request to [$url] failed with status code ${response.statusCode} & result : \n $data', name: 'Request fail error', ); isSuccess = false;