mobile-app/lib/helper/UseApi.dart

98 lines
2.2 KiB
Dart
Raw Permalink Normal View History

2024-10-21 12:33:46 +00:00
// ignore_for_file: file_names
import 'dart:convert';
import 'package:daily_ledger/config/Global.dart';
import 'package:http/http.dart' as http;
class ApiService {
late final String token;
ApiService(this.token);
String getApi(String apiName) {
return Constants.baseUrl + Constants.apiEndpoints[apiName]!;
}
Future<http.Response> post(String api, Map<String, dynamic> payload) async {
final uri = Uri.parse(getApi(api));
try {
final response = await http.post(
uri,
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
body: jsonEncode(payload),
);
return response;
} catch (err) {
rethrow;
}
}
Future<http.Response> put(
String api, String id, Map<String, dynamic> payload) async {
final uri = Uri.parse('${getApi(api)}$id/');
try {
final response = await http.put(
uri,
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
body: jsonEncode(payload),
);
return response;
} catch (err) {
rethrow;
}
}
Future<http.Response> patch(
String api, String id, Map<String, dynamic> payload) async {
final uri = Uri.parse('${getApi(api)}$id/');
try {
final response = await http.patch(
uri,
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
body: jsonEncode(payload),
);
return response;
} catch (err) {
rethrow;
}
}
Future<dynamic> get(String api) async {
final uri = Uri.parse(getApi(api));
try {
final response = await http.get(
uri,
headers: {
'Authorization': 'Bearer $token',
},
);
return jsonDecode(response.body);
} catch (err) {
rethrow;
}
}
Future<http.Response> delete(String api, String id) async {
final uri = Uri.parse('${getApi(api)}$id/');
try {
final response = await http.delete(
uri,
headers: {
'Authorization': 'Bearer $token',
},
);
return response;
} catch (err) {
rethrow;
}
}
}