-
Notifications
You must be signed in to change notification settings - Fork 7
/
repository_example.dart
executable file
·44 lines (36 loc) · 1.1 KB
/
repository_example.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import 'package:either_option/either_option.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'model/server_error.dart';
import 'model/user.dart';
class Repository {
// With Either
Future<Either<ServerError, User>> getUser(int id) async {
final baseUrl =
Uri.parse("https://fakerestapi.azurewebsites.net/api/Users/$id");
User user;
final res = await http.get(baseUrl);
if (res.statusCode == 200) {
dynamic body = json.decode(res.body);
user = User.fromJson(body);
return Right(user);
}
if (res.statusCode == 404)
return Left(ServerError("This user doesn't exist"));
return Left(ServerError("unknown server error"));
}
// With Option
Future<Option<User>> getUserOpt(int id) async {
final baseUrl =
Uri.parse("https://fakerestapi.azurewebsites.net/api/Users/$id");
User user;
final res = await http.get(baseUrl);
if (res.statusCode == 200) {
dynamic body = json.decode(res.body);
user = User.fromJson(body);
return Some(user);
}
return None();
}
}