]> git.cworth.org Git - lmno.games/commitdiff
flempires: Create new class WebService.dart
authorKevin Worth <kworth082@gmail.com>
Tue, 26 May 2020 11:33:07 +0000 (07:33 -0400)
committerKevin Worth <kworth082@gmail.com>
Mon, 6 Jul 2020 12:35:26 +0000 (08:35 -0400)
This will allow us to avoid reinventing the wheel each time there's a
new web api endpoint to fetch from.

flempires/lib/WebService.dart [new file with mode: 0644]

diff --git a/flempires/lib/WebService.dart b/flempires/lib/WebService.dart
new file mode 100644 (file)
index 0000000..d189a4e
--- /dev/null
@@ -0,0 +1,23 @@
+import 'package:http/http.dart' as http;
+import 'package:http/http.dart';
+
+class Request<T> {
+  final String url;
+  T Function(Response response) parse;
+  final String type;
+
+  Request({this.url, this.parse, this.type});
+}
+
+class WebService {
+  Future<T> fetch<T>(Request<T> request) async {
+    final response = await http.get(request.url);
+
+    if (response.statusCode == 200) {
+      return request.parse(response);
+    } else {
+      throw Exception(
+          'Failed to fetch ' + request.type + ' from url ' + request.url);
+    }
+  }
+}