Files
2025-10-23 08:19:18 +02:00

92 lines
2.6 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../../main.dart'; // kApiBase
import '../../auth/data/token_storage.dart'; // tokenStorageProvider
import '../domain/messwert.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class MesswerteRepository {
MesswerteRepository(this._tokens);
final TokenStorage _tokens;
Future<List<Messwert>> list(int igelId) async {
final t = await _tokens.access;
final r = await http.get(
Uri.parse('$kApiBase/igel/$igelId/messwerte'),
headers: {'Authorization': 'Bearer $t'},
);
if (r.statusCode != 200) {
throw Exception('API ${r.statusCode}: ${r.body}');
}
final List data = jsonDecode(r.body) as List;
return data
.map((e) => Messwert.fromMap(e as Map<String, dynamic>))
.toList();
}
Future<void> create({
required int igelId,
required DateTime datum,
required int gewicht,
String? behandlung,
String? bemerkung,
}) async {
final t = await _tokens.access;
final r = await http.post(
Uri.parse('$kApiBase/igel/$igelId/messwerte'),
headers: {
'Authorization': 'Bearer $t',
'Content-Type': 'application/json',
},
body: jsonEncode({
'datum': datum.toUtc().toIso8601String(),
'gewicht': gewicht,
'behandlung': behandlung,
'bemerkung': bemerkung,
}),
);
if (r.statusCode != 201) {
throw Exception('API ${r.statusCode}: ${r.body}');
}
}
Future<void> update(int id, Messwert m) async {
final t = await _tokens.access;
final r = await http.put(
Uri.parse('$kApiBase/messwerte/$id'),
headers: {
'Authorization': 'Bearer $t',
'Content-Type': 'application/json',
},
body: jsonEncode({
// Wichtig: KEIN 'id' im Body mitschicken der steht bereits in der URL!
'datum': m.datum.toUtc().toIso8601String(),
'gewicht': m.gewicht,
'behandlung': m.behandlung,
'bemerkung': m.bemerkung,
}),
);
if (r.statusCode != 200) {
throw Exception('API ${r.statusCode}: ${r.body}');
}
}
Future<void> delete(int id) async {
final t = await _tokens.access;
final r = await http.delete(
Uri.parse('$kApiBase/messwerte/$id'),
headers: {'Authorization': 'Bearer $t'},
);
if (r.statusCode != 200) {
throw Exception('API ${r.statusCode}: ${r.body}');
}
}
}
// Riverpod Provider
final messwerteRepoProvider = Provider<MesswerteRepository>((ref) {
final tokens = ref.read(tokenStorageProvider);
return MesswerteRepository(tokens);
});