Load server configuration
This commit is contained in:
72
moneymgr_mobile/lib/services/api/server_api.dart
Normal file
72
moneymgr_mobile/lib/services/api/server_api.dart
Normal file
@ -0,0 +1,72 @@
|
||||
// ignore_for_file: non_constant_identifier_names
|
||||
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:moneymgr_mobile/services/storage/prefs.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'api_client.dart';
|
||||
|
||||
part 'server_api.freezed.dart';
|
||||
part 'server_api.g.dart';
|
||||
|
||||
@freezed
|
||||
abstract class ServerConstraint with _$ServerConstraint {
|
||||
const factory ServerConstraint({required int min, required int max}) =
|
||||
_ServerConstraint;
|
||||
|
||||
factory ServerConstraint.fromJson(Map<String, dynamic> json) =>
|
||||
_$ServerConstraintFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ServerConstraints with _$ServerConstraints {
|
||||
const factory ServerConstraints({required ServerConstraint inbox_entry_label}) =
|
||||
_ServerConstraints;
|
||||
|
||||
factory ServerConstraints.fromJson(Map<String, dynamic> json) =>
|
||||
_$ServerConstraintsFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ServerConfig with _$ServerConfig {
|
||||
const factory ServerConfig({required ServerConstraints constraints}) =
|
||||
_ServerConfig;
|
||||
|
||||
factory ServerConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$ServerConfigFromJson(json);
|
||||
}
|
||||
|
||||
/// Auth API
|
||||
extension ServerApi on ApiClient {
|
||||
/// Get authentication information from server
|
||||
Future<ServerConfig> serverConfig() async {
|
||||
final response = await execute("/server/config", method: "GET");
|
||||
return ServerConfig.fromJson(response.data);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// Get authentication information from server, or retrieve cached information (if available, in
|
||||
/// case of failure)
|
||||
@riverpod
|
||||
Future<ServerConfig> serverConfigOrCache(Ref ref) async {
|
||||
final client = ref.watch(apiServiceProvider)!;
|
||||
try {
|
||||
final config = await client.serverConfig();
|
||||
client.prefs.setServerConfig(config);
|
||||
return config;
|
||||
} catch (e, s) {
|
||||
Logger.root.warning("Failed to fetch server configuration! $e $s");
|
||||
}
|
||||
|
||||
final cached = client.prefs.serverConfig();
|
||||
if (cached == null) {
|
||||
throw Exception(
|
||||
"Could not fetch server configuration, cached version is unavailable!",
|
||||
);
|
||||
}
|
||||
return cached;
|
||||
}
|
Reference in New Issue
Block a user