62 lines
2.0 KiB
Dart
62 lines
2.0 KiB
Dart
import 'package:http/http.dart' as http;
|
|
import 'dart:convert';
|
|
import 'package:timezone/timezone.dart' as tz;
|
|
|
|
import '../model/flood_station.dart';
|
|
import '../model/reading.dart';
|
|
|
|
class Api {
|
|
static const String _rootUrl =
|
|
'https://environment.data.gov.uk/flood-monitoring';
|
|
|
|
static Future<List<FloodStation>> fetchAllStations() async {
|
|
List<FloodStation> stations = [];
|
|
final response = await http.get(Uri.parse('$_rootUrl/id/stations'));
|
|
if (response.statusCode == 200) {
|
|
final Map<String, dynamic> jsonStr = jsonDecode(response.body);
|
|
for (final str in jsonStr['items']) {
|
|
stations.add(FloodStation.fromMap(str));
|
|
}
|
|
}
|
|
return stations;
|
|
}
|
|
|
|
/// [limit] limits the number of entries that are requested from the API and [offset] returns the
|
|
/// list starting from the specified number
|
|
|
|
static Future<List<FloodStation>> fetchStationsByRange(
|
|
int limit, int offset) async {
|
|
List<FloodStation> stations = [];
|
|
final response = await http
|
|
.get(Uri.parse('$_rootUrl/id/stations?_limit=$limit&_offset=$offset'));
|
|
if (response.statusCode == 200) {
|
|
final Map<String, dynamic> jsonStr = jsonDecode(response.body);
|
|
for (final str in jsonStr['items']) {
|
|
stations.add(FloodStation.fromMap(str));
|
|
}
|
|
}
|
|
return stations;
|
|
}
|
|
|
|
static Future<List<Reading>> fetchReadingsFromStation(
|
|
String stationId) async {
|
|
List<Reading> readings = [];
|
|
final dateTime = _getCurrentUKTime().subtract(Duration(days: 1)).toUtc();
|
|
final url =
|
|
'$_rootUrl/id/stations/$stationId/readings?since=${dateTime.toIso8601String()}&_sorted';
|
|
final response = await http.get(Uri.parse(url));
|
|
if (response.statusCode == 200) {
|
|
final Map<String, dynamic> jsonStr = jsonDecode(response.body);
|
|
for (final str in jsonStr['items']) {
|
|
readings.add(Reading.fromMap(str));
|
|
}
|
|
}
|
|
return readings.reversed.toList();
|
|
}
|
|
|
|
static DateTime _getCurrentUKTime() {
|
|
final london = tz.getLocation('Europe/London');
|
|
return tz.TZDateTime.now(london);
|
|
}
|
|
}
|