-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsplash_repository.dart
74 lines (66 loc) · 2.16 KB
/
splash_repository.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/res/errors.dart';
import '../../core/res/strings.dart';
import '../../core/utils/injection.dart';
import '../../core/utils/logger.dart';
import '../../models/user.dart';
@immutable
abstract class SplashRepository {
/// Fetches `Token` from Shared Preferences , gives the user details and throws a suitable exception if something goes wrong.
Future<User> getProfile();
}
class FakeSplashRepository extends SplashRepository {
@override
Future<User> getProfile() async {
// Simulate network delay
await Future.delayed(Duration(seconds: 1));
if (Random().nextBool()) {
// random network error
throw NetworkException();
} else {
var response = {
S.firstnameKey: "Sahil",
S.lastnameKey: "Silare",
S.emailKey: "[email protected]",
S.phoneKey: "9999999999",
};
// fake successful response (the data entered here same as in the API Doc example)
return User.fromJson(response);
}
}
}
class APISplashRepository extends SplashRepository {
final String classTag = "APISplashRepository";
@override
Future<User> getProfile() async {
final SharedPreferences sharedPreferences = sl.get<SharedPreferences>();
String? token = sharedPreferences.getString(S.tokenKeySharedPreferences);
final String tag = classTag + "getUserDetails";
http.Response response;
try {
response = await sl
.get<http.Client>()
.get(Uri.parse(S.getUserDetailsUrl), headers: <String, String>{
"Authorization": "$token",
});
} catch (e) {
throw NetworkException();
}
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
} else if (response.statusCode == 401) {
throw ValidationException(response.body);
} else {
Log.s(
tag: tag,
message:
"Unknown response code -> ${response.statusCode}, message ->" +
response.body);
throw UnknownException();
}
}
}