a1f67e71e2
Signed-off-by: Hans Kokx <hans.d.kokx@gmail.com>
95 lines
2.7 KiB
Dart
95 lines
2.7 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:intl/intl.dart';
|
|
|
|
class ForexConversionResult {
|
|
ForexConversionResult({required this.quote, required this.result});
|
|
|
|
final double quote;
|
|
final double result;
|
|
}
|
|
|
|
class ForexRateApiService {
|
|
ForexRateApiService({required this.httpClient, required this.apiKey});
|
|
|
|
final http.Client httpClient;
|
|
final String apiKey;
|
|
|
|
Future<double> fetchUsdToSekRate({required DateTime estDate}) async {
|
|
if (apiKey == 'REPLACE_WITH_YOUR_FOREXRATE_API_KEY') {
|
|
throw StateError('ForexRateAPI key is not configured.');
|
|
}
|
|
|
|
final date = DateFormat('yyyy-MM-dd').format(estDate);
|
|
final uri = Uri.https('api.forexrateapi.com', '/v1/$date', <String, String>{
|
|
'api_key': apiKey,
|
|
'base': 'USD',
|
|
'currencies': 'SEK',
|
|
});
|
|
|
|
final response = await httpClient.get(uri);
|
|
if (response.statusCode != 200) {
|
|
throw StateError('ForexRateAPI request failed (${response.statusCode}).');
|
|
}
|
|
|
|
final json = jsonDecode(response.body) as Map<String, dynamic>;
|
|
final success = json['success'] as bool? ?? false;
|
|
if (!success) {
|
|
throw StateError('ForexRateAPI returned success=false.');
|
|
}
|
|
|
|
final rates = json['rates'] as Map<String, dynamic>?;
|
|
final sek = rates?['SEK'];
|
|
if (sek == null) {
|
|
throw StateError('SEK rate was missing in API response.');
|
|
}
|
|
|
|
return (sek as num).toDouble();
|
|
}
|
|
|
|
Future<ForexConversionResult> convertUsdToSek({
|
|
required DateTime estDate,
|
|
required double amount,
|
|
}) async {
|
|
if (apiKey == 'REPLACE_WITH_YOUR_FOREXRATE_API_KEY') {
|
|
throw StateError('ForexRateAPI key is not configured.');
|
|
}
|
|
|
|
final date = DateFormat('yyyy-MM-dd').format(estDate);
|
|
final uri =
|
|
Uri.https('api.forexrateapi.com', '/v1/convert', <String, String>{
|
|
'api_key': apiKey,
|
|
'from': 'USD',
|
|
'to': 'SEK',
|
|
'amount': amount.toStringAsFixed(2),
|
|
'date': date,
|
|
});
|
|
|
|
final response = await httpClient.get(uri);
|
|
if (response.statusCode != 200) {
|
|
throw StateError('ForexRateAPI convert failed (${response.statusCode}).');
|
|
}
|
|
|
|
final json = jsonDecode(response.body) as Map<String, dynamic>;
|
|
final success = json['success'] as bool? ?? false;
|
|
if (!success) {
|
|
throw StateError('ForexRateAPI convert returned success=false.');
|
|
}
|
|
|
|
final info = json['info'] as Map<String, dynamic>?;
|
|
final quote = info?['quote'];
|
|
final result = json['result'];
|
|
if (quote == null || result == null) {
|
|
throw StateError(
|
|
'ForexRateAPI convert response was missing quote/result.',
|
|
);
|
|
}
|
|
|
|
return ForexConversionResult(
|
|
quote: (quote as num).toDouble(),
|
|
result: (result as num).toDouble(),
|
|
);
|
|
}
|
|
}
|