Skip to content

Commit

Permalink
build: sonar high issues fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
cevheri committed Nov 20, 2024
1 parent 9ef8d15 commit 23e7a09
Show file tree
Hide file tree
Showing 9 changed files with 356 additions and 336 deletions.
54 changes: 29 additions & 25 deletions lib/data/http_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,21 @@ class MyHttpOverrides extends HttpOverrides {

class HttpUtils {
static String errorHeader = 'x-${ProfileConstants.isProduction == true ? AppConstants.APP_KEY : "default_token"}App-error';
static String successResult = 'success';
static String keyForJWTToken = 'jwt-token';
static String badRequestServerKey = 'error.400';
static String errorServerKey = 'error.500';
static const String successResult = 'success';
static const String keyForJWTToken = 'jwt-token';
static const String badRequestServerKey = 'error.400';
static const String errorServerKey = 'error.500';
static const String generalNoErrorKey = 'none';
static int timeout = 30;
static const int timeout = 30;
static const String applicationJson = 'application/json';
static const String UTF8 = 'utf-8';
static const String noInternetConnectionError = 'No Internet connection';
static const String requestTimeoutError = 'Request timeout';

/// -H 'accept: application/json, text/plain, */*' \
/// -H 'content-type: application/json' \
/// Default headers for all requests (can be overridden with [addCustomHttpHeader])
static final _defaultHttpHeaders = {'Accept': 'application/json', 'Content-Type': 'application/json'};
static final _defaultHttpHeaders = {'Accept': applicationJson, 'Content-Type': applicationJson};

static final _customHttpHeaders = <String, String>{};

Expand Down Expand Up @@ -87,10 +91,10 @@ class HttpUtils {
var headers = await HttpUtils.headers();
String messageBody = "";

if (headers['Content-Type'] == 'application/json') {
if (headers['Content-Type'] == applicationJson) {
messageBody = JsonMapper.serialize(
body,
SerializationOptions(
const SerializationOptions(
indent: '',
ignoreDefaultMembers: true,
ignoreNullMembers: true,
Expand All @@ -110,17 +114,17 @@ class HttpUtils {
url,
headers: headers,
body: messageBody,
encoding: Encoding.getByName('utf-8'),
encoding: Encoding.getByName(UTF8),
)
.timeout(Duration(seconds: timeout));

checkUnauthorizedAccess(endpoint, response);
} on SocketException catch (se) {
debugPrint("Socket Exception: $se");
throw FetchDataException('No Internet connection');
throw FetchDataException(noInternetConnectionError);
} on TimeoutException catch (toe) {
debugPrint("Timeout Exception: $toe");
throw FetchDataException('Request timeout');
throw FetchDataException(requestTimeoutError);
}

return response;
Expand All @@ -143,9 +147,9 @@ class HttpUtils {
checkUnauthorizedAccess(endpoint, response);
return response;
} on SocketException {
throw FetchDataException('No Internet connection');
throw FetchDataException(noInternetConnectionError);
} on TimeoutException {
throw FetchDataException('Request timeout');
throw FetchDataException(requestTimeoutError);
}
}

Expand All @@ -165,9 +169,9 @@ class HttpUtils {
// int countOffers = int.parse(result.headers['x-total-count']!);
// return countOffers;
// } on SocketException {
// throw FetchDataException('No Internet connection');
// throw FetchDataException(noInternetConnectionError);
// } on TimeoutException {
// throw FetchDataException('Request timeout');
// throw FetchDataException(requestTimeoutError);
// }
// }

Expand All @@ -176,7 +180,7 @@ class HttpUtils {
var headers = await HttpUtils.headers();
final String json = JsonMapper.serialize(
body,
SerializationOptions(
const SerializationOptions(
indent: '',
ignoreDefaultMembers: true,
ignoreNullMembers: true,
Expand All @@ -186,13 +190,13 @@ class HttpUtils {
http.Response response;
try {
response = await http
.put(Uri.parse('${ProfileConstants.api}$endpoint'), headers: headers, body: json, encoding: Encoding.getByName('utf-8'))
.put(Uri.parse('${ProfileConstants.api}$endpoint'), headers: headers, body: json, encoding: Encoding.getByName(UTF8))
.timeout(Duration(seconds: timeout));
checkUnauthorizedAccess(endpoint, response);
} on SocketException {
throw FetchDataException('No Internet connection');
throw FetchDataException(noInternetConnectionError);
} on TimeoutException {
throw FetchDataException('Request timeout');
throw FetchDataException(requestTimeoutError);
}
return response;
}
Expand All @@ -202,7 +206,7 @@ class HttpUtils {
var headers = await HttpUtils.headers();
final String json = JsonMapper.serialize(
body,
SerializationOptions(
const SerializationOptions(
indent: '',
ignoreDefaultMembers: true,
ignoreNullMembers: true,
Expand All @@ -212,13 +216,13 @@ class HttpUtils {
http.Response response;
try {
response = await http
.patch(Uri.parse('${ProfileConstants.api}$endpoint'), headers: headers, body: json, encoding: Encoding.getByName('utf-8'))
.patch(Uri.parse('${ProfileConstants.api}$endpoint'), headers: headers, body: json, encoding: Encoding.getByName(UTF8))
.timeout(Duration(seconds: timeout));
checkUnauthorizedAccess(endpoint, response);
} on SocketException {
throw FetchDataException('No Internet connection');
throw FetchDataException(noInternetConnectionError);
} on TimeoutException {
throw FetchDataException('Request timeout');
throw FetchDataException(requestTimeoutError);
}
return response;
}
Expand All @@ -231,9 +235,9 @@ class HttpUtils {
checkUnauthorizedAccess(endpoint, response);
return response;
} on SocketException {
throw FetchDataException('No Internet connection');
throw FetchDataException(noInternetConnectionError);
} on TimeoutException {
throw FetchDataException('Request timeout');
throw FetchDataException(requestTimeoutError);
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/data/models/city.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class City extends Equatable {
}

static City? fromJson(Map<String, dynamic> json) {
return City().copyWith(
return const City().copyWith(
id: json['id'],
name: json['name'],
plateCode: json['plateCode'],
Expand Down
2 changes: 1 addition & 1 deletion lib/data/models/district.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class District extends Equatable {
}

static District? fromJson(Map<String, dynamic> json) {
return District().copyWith(
return const District().copyWith(
id: json['id'],
name: json['name'],
code: json['code'],
Expand Down
9 changes: 5 additions & 4 deletions lib/data/repository/account_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import 'package:flutter_bloc_advance/data/models/user.dart';
class AccountRepository {
AccountRepository();

final String _resource = "account";
static const _resource = "account";
static const userIdNotNull = "User id not null";

Future<User?> register(User? newUser) async {
debugPrint("register repository start");
Expand Down Expand Up @@ -76,7 +77,7 @@ class AccountRepository {
throw BadRequestException("User null");
}
if (user.id == null || user.id!.isEmpty) {
throw BadRequestException("User id not null");
throw BadRequestException(userIdNotNull);
}
final httpResponse = await HttpUtils.postRequest<User>("/$_resource", user);
final response = HttpUtils.decodeUTF8(httpResponse.body.toString());
Expand All @@ -88,7 +89,7 @@ class AccountRepository {
Future<User> updateAccount(User account) async {
debugPrint("BEGIN:updateAccount repository start");
if (account.id == null || account.id!.isEmpty) {
throw BadRequestException("User id not null");
throw BadRequestException(userIdNotNull);
}
final response = await HttpUtils.putRequest<User>("/$_resource", account);
final result = User.fromJsonString(response.body.toString())!;
Expand All @@ -99,7 +100,7 @@ class AccountRepository {
Future<bool> deleteAccount(String id) async {
debugPrint("BEGIN:deleteAccount repository start");
if (id.isEmpty) {
throw BadRequestException("User id not null");
throw BadRequestException(userIdNotNull);
}
var result = await HttpUtils.deleteRequest("/$_resource/$id");
debugPrint("END:deleteAccount successful - response : ${result.body.toString()}");
Expand Down
9 changes: 5 additions & 4 deletions lib/data/repository/user_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import '../models/user.dart';
/// This class is responsible for all the user related operations
/// list, create, update, delete etc.
class UserRepository {
final String _resource = "users";
static const String _resource = "users";
static const String userIdRequired = "User id is required";

/// Retrieve all users method that retrieves all the users
Future<List<User?>> getUsers({int page = 0, int size = 10, List<String> sort = const ["id,desc"]}) async {
Expand All @@ -27,7 +28,7 @@ class UserRepository {
Future<User?> getUser(String id) async {
debugPrint("BEGIN:getUser repository start");
if (id.isEmpty) {
throw BadRequestException("User id is required");
throw BadRequestException(userIdRequired);
}
final httpResponse = await HttpUtils.getRequest("/admin/$_resource/$id");
final response = User.fromJsonString(httpResponse.body)!;
Expand Down Expand Up @@ -92,7 +93,7 @@ class UserRepository {
Future<User?> updateUser(User user) async {
debugPrint("BEGIN:updateUser repository start");
if(user.id == null || user.id!.isEmpty) {
throw BadRequestException("User id is required");
throw BadRequestException(userIdRequired);
}
final httpResponse = await HttpUtils.putRequest<User>("/admin/$_resource", user);
final response = User.fromJsonString(httpResponse.body);
Expand All @@ -103,7 +104,7 @@ class UserRepository {
Future<void> deleteUser(String id) async {
debugPrint("BEGIN:deleteUser repository start");
if(id.isEmpty) {
throw BadRequestException("User id is required");
throw BadRequestException(userIdRequired);
}
await HttpUtils.deleteRequest("/admin/$_resource/$id");
debugPrint("END:deleteUser successful");
Expand Down
10 changes: 4 additions & 6 deletions lib/main/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,18 @@ class App extends StatelessWidget {
routes: {
ApplicationRoutes.home: (context) {
return BlocProvider<AccountBloc>(
create: (context) => AccountBloc(accountRepository: AccountRepository())..add(AccountLoad()), child: HomeScreen());
create: (context) => AccountBloc(accountRepository: AccountRepository())..add(const AccountLoad()), child: HomeScreen());
},
ApplicationRoutes.account: (context) {
return BlocProvider<AccountBloc>(
create: (context) => AccountBloc(accountRepository: AccountRepository())..add(AccountLoad()), child: AccountsScreen());
create: (context) => AccountBloc(accountRepository: AccountRepository())..add(const AccountLoad()), child: AccountsScreen());
},
ApplicationRoutes.login: (context) {
return BlocProvider<LoginBloc>(create: (context) => LoginBloc(loginRepository: LoginRepository()), child: LoginScreen());
},
ApplicationRoutes.settings: (context) {
return BlocProvider<SettingsBloc>(
create: (context) => SettingsBloc(accountRepository: AccountRepository()), child: SettingsScreen());
create: (context) => SettingsBloc(accountRepository: AccountRepository()), child: const SettingsScreen());
},
ApplicationRoutes.forgotPassword: (context) {
return BlocProvider<ForgotPasswordBloc>(
Expand All @@ -115,9 +115,7 @@ class App extends StatelessWidget {
return BlocProvider<ChangePasswordBloc>(
create: (context) => ChangePasswordBloc(accountRepository: AccountRepository()), child: ChangePasswordScreen());
},
ApplicationRoutes.logout: (context) {
return LogoutConfirmationDialog();
},
ApplicationRoutes.logout: (context) => const LogoutConfirmationDialog(),
ApplicationRoutes.createUser: (context) {
return BlocProvider<UserBloc>(create: (context) => UserBloc(userRepository: UserRepository()), child: CreateUserScreen());
},
Expand Down
Loading

0 comments on commit 23e7a09

Please sign in to comment.