didvan-app/lib/services/network/request.dart

198 lines
4.8 KiB
Dart

import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:http/http.dart' as http;
class RequestService {
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;
final Map<String, String> _headers = {
"accept": "*/*",
"Content-Type": "application/json; charset=UTF-8",
};
final String url;
dynamic _requestBody;
bool isSuccess = false;
RequestService(
this.url, {
Map<String, String>? requestHeaders,
body,
bool useAutherization = true,
}) {
if (body != null) _requestBody = body;
if (requestHeaders != null) _headers.addAll(requestHeaders);
if (useAutherization) _headers.addAll({'Authorization': 'Bearer $_token'});
if (body != null) _requestBody = body;
}
Future<void> httpGet() async {
try {
final response = await http
.get(
Uri.parse(url),
headers: _headers,
)
.timeout(
const Duration(seconds: 10),
)
.catchError(
(e) => throw e,
);
_handleResponse(response);
} catch (e) {
_handleError(null);
}
}
Future<void> post() async {
try {
final response = await http
.post(
Uri.parse(url),
body: json.encode(_requestBody),
headers: _headers,
)
.timeout(
const Duration(seconds: 10),
)
.catchError(
(e) {
throw e;
},
);
_handleResponse(response);
} catch (e) {
_handleError(null);
}
}
Future<void> delete() async {
try {
final response = await http
.delete(
Uri.parse(url),
body: json.encode(_requestBody),
headers: _headers,
)
.timeout(
const Duration(seconds: 10),
)
.catchError(
(e) => throw e,
);
_handleResponse(response);
} catch (e) {
_handleError(null);
}
}
Future<void> multipart(File file) async {
try {
final request = http.MultipartRequest('POST', Uri.parse(url));
_headers.update('Content-Type', (_) => 'multipart/form-data');
request.headers.addAll(_headers);
request.files.add(
http.MultipartFile(
'file',
file.readAsBytes().asStream(),
file.lengthSync(),
filename: 'desc',
),
);
final streamedResponse = await request
.send()
.timeout(
const Duration(seconds: 10),
)
.catchError(
(e) => throw e,
);
final response = await http.Response.fromStream(streamedResponse);
_handleResponse(response);
} catch (e) {
_handleError(null);
}
}
Future<void> put() async {
try {
final response = await http
.put(
Uri.parse(url),
body: json.encode(_requestBody),
headers: _headers,
)
.timeout(
const Duration(seconds: 10),
)
.catchError(
(e) => throw e,
);
_handleResponse(response);
} catch (e) {
_handleError(null);
}
}
void _handleResponse(http.Response? response) {
if (_handleError(response)) {
if (response!.body.isNotEmpty) {
_body = json.decode(response.body);
}
}
errorMessage = _errorMessageGenerator(response);
}
bool _handleError(http.Response? response) {
if (response == null) {
log(
'Connecion failed or request timedout! ("$url")',
name: 'Request fail error',
);
isSuccess = false;
return false;
}
if (response.statusCode != 200) {
dynamic data;
if (response.body.isEmpty) {
data = 'No results!';
} else if (response.body.contains('<!DOCTYPE html>')) {
data = response.body;
} else {
data = jsonDecode(response.body);
}
log(
'Request to [$url] failed with status code ${response.statusCode} & result : \n $data',
name: 'Request fail error',
);
isSuccess = false;
return false;
}
isSuccess = true;
return true;
}
String _errorMessageGenerator(http.Response? response) {
String? error;
if (response != null) {
if (!response.body.contains('<!DOCTYPE html>')) {
if (result.isNotEmpty) {
error = result['msg'];
}
}
}
return error ?? 'خطا! لطفا اتصال اینترنت خود را بررسی و مجددا تلاش نمایید.';
}
}