Skip to content

Instantly share code, notes, and snippets.

@AndresR173
Created May 19, 2021 15:55
Show Gist options
  • Save AndresR173/6860dfcbaee5c9513ec8fecc5bafc5d9 to your computer and use it in GitHub Desktop.
Save AndresR173/6860dfcbaee5c9513ec8fecc5bafc5d9 to your computer and use it in GitHub Desktop.
Http wrapper for Dart
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../../utils/constants.dart';
import '../../utils/error/failure.dart';
import '../../utils/extensions/extensions.dart';
import '../../utils/injection_container.dart';
import '../../utils/logging.dart';
import '../../utils/preferences_manager.dart';
class HttpService with Logging {
BuildContext? context;
Map<String, String> _getHeaders() {
final Map<String, String> headers = {
'content-Type': 'application/json',
};
final PreferencesManager prefManager = sl();
final token = prefManager.user?.token ?? '';
if (token.isNotEmpty) {
headers['Authorization'] = 'Bearer $token';
}
if (sl.isRegistered<Locale>()) {
final languageCode = sl<Locale>().languageCode;
headers['language'] = languageCode;
}
return headers;
}
Future<T?> get<T>({
required String path,
int? page,
required T? Function(Map<String, dynamic>?)? handler,
}) async {
try {
String url = '$baseUrl$path';
if (page != null) url += '?page=$page';
final response = await http.get(Uri.parse(url), headers: _getHeaders());
if (response.isSuccess) {
final data =
handler?.call(jsonDecode(response.body) as Map<String, dynamic>?);
return data;
} else {
throw const ServerFailure();
}
} on SocketException catch (_) {
rethrow;
} catch (e) {
throw UnknownFailure(e.toString());
}
}
Future<bool> delete<T>({required String path}) async {
try {
final url = '$baseUrl$path';
final response =
await http.delete(Uri.parse(url), headers: _getHeaders());
return response.isSuccess;
} catch (e) {
throw UnknownFailure(e.toString());
}
}
Future<T> getWithId<T>({
required int id,
required String path,
required T Function(Map<String, dynamic>?) handler,
}) async {
try {
final url = '$baseUrl$path/$id';
final response = await http.get(Uri.parse(url), headers: _getHeaders());
if (response.isSuccess) {
final data =
handler(jsonDecode(response.body) as Map<String, dynamic>?);
return data;
} else {
throw const ServerFailure();
}
} catch (e) {
throw UnknownFailure(e.toString());
}
}
Future<T?> post<T>({
required String path,
required T? Function(Map<String, dynamic>?)? handler,
}) async {
try {
final url = '$baseUrl$path';
final response = await http.post(Uri.parse(url), headers: _getHeaders());
if (response.isSuccess) {
if (T == bool && handler == null) {
return response.isSuccess as T;
}
final data =
handler?.call(jsonDecode(response.body) as Map<String, dynamic>?);
return data;
} else {
final data = jsonDecode(response.body) as Map<String, dynamic>;
throw ServerFailure(errorMessage: data['error'] as String?);
}
} catch (e) {
rethrow;
}
}
Future<T?> postWith<T>({
required String path,
required Map<String, dynamic> data,
required T Function(Map<String, dynamic>?)? handler,
}) async {
try {
final url = '$baseUrl$path';
final response = await http.post(Uri.parse(url),
body: jsonEncode(data), headers: _getHeaders());
if (response.isSuccess) {
if (T == bool && handler == null) {
return response.isSuccess as T;
}
final data =
handler?.call(jsonDecode(response.body) as Map<String, dynamic>?);
return data;
} else {
final data = jsonDecode(response.body) as Map<String, dynamic>;
throw ServerFailure(errorMessage: data['error'] as String?);
}
} catch (e) {
rethrow;
}
}
Future<T?> patchWith<T>({
required String path,
required Map<String, dynamic> data,
required T Function(Map<String, dynamic>?)? handler,
}) async {
try {
final url = '$baseUrl$path';
final response = await http.patch(Uri.parse(url),
body: jsonEncode(data), headers: _getHeaders());
if (response.isSuccess) {
final data =
handler?.call(jsonDecode(response.body) as Map<String, dynamic>?);
return data;
} else {
final data = jsonDecode(response.body) as Map<String, dynamic>;
throw ServerFailure(errorMessage: data['error'] as String?);
}
} catch (e) {
rethrow;
}
}
Future<Map<String, dynamic>?> uploadFile({
required String path,
required File file,
required String paramName,
Map<String, String?>? fields,
String method = 'POST',
}) async {
final url = Uri.parse('$baseUrl$path');
final request = http.MultipartRequest(method, url);
final token = sl<PreferencesManager>().user?.token;
request.headers['Authorization'] = 'Bearer $token';
fields?.forEach((key, value) {
request.fields[key] = value!;
});
try {
final fileName = file.path.split('/').last;
final fileContent = await file.readAsBytes();
final multipartFile = http.MultipartFile.fromBytes(paramName, fileContent,
filename: fileName);
request.files.add(multipartFile);
final responseStream = await request.send();
final responseString = await responseStream.stream.bytesToString();
final jsonMap = json.decode(responseString) as Map<String, dynamic>?;
return jsonMap;
} catch (error) {
log.d(error);
rethrow;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment