added fpdart demo

This commit is contained in:
2024-11-27 15:59:08 +01:00
parent 89e12bdf9f
commit caf6007c26
10 changed files with 755 additions and 254 deletions
@@ -0,0 +1,46 @@
import 'package:fpdart/fpdart.dart';
// Fehlerkategorien
enum AppErrorType {
ValidationError,
DatabaseError,
NetworkError,
UnknownError,
}
class AppError {
final String message; // Benutzerfreundliche Fehlermeldung
final AppErrorType type; // Typisierte Fehlerkategorie
final Exception? exception; // Originale Exception (falls vorhanden)
AppError({
required this.message,
this.type = AppErrorType.UnknownError,
this.exception,
});
@override
String toString() {
return 'AppError(message: $message, type: $type, exception: $exception)';
}
/// Hilfsmethode zur einfachen Erstellung eines `Left`-Werts für `Either`
static Either<AppError, T> left<T>(
String message, {
AppErrorType? type,
Exception? exception,
}) {
return Either.left(AppError(
message: message,
type: type ?? AppErrorType.UnknownError,
exception: exception,
));
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is AppError && other.message == message && other.type == type;
}
}
@@ -0,0 +1,68 @@
import 'package:demo/app_error.dart';
import 'package:fpdart/fpdart.dart';
// Mock-Datenbank
final existingEmails = ["existing@example.com"];
// Validierungsfunktionen
Either<AppError, String> validateName(String name) {
return name.isNotEmpty
? Either.right(name)
: AppError.left(
"Name cannot be empty",
type: AppErrorType.ValidationError,
);
}
Either<AppError, String> validateEmail(String email) {
final emailRegex = RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+");
return emailRegex.hasMatch(email)
? Either.right(email)
: AppError.left(
"Invalid email format",
type: AppErrorType.ValidationError,
);
}
// Asynchrone Überprüfung, ob die E-Mail bereits existiert
TaskEither<AppError, bool> checkEmailExists(String email) {
return TaskEither.tryCatch(
() async => existingEmails.contains(email),
(error, _) => AppError(
message: "Error checking email existence",
type: AppErrorType.DatabaseError,
exception: error as Exception?,
),
);
}
// Benutzer in der Datenbank speichern (Dummy-Implementierung)
TaskEither<AppError, bool> saveUser(String name, String email) {
return TaskEither.tryCatch(
() async {
await Future.delayed(Duration(seconds: 1)); // Simulierte Latenz
print("User saved: $name, $email");
return true;
},
(error, _) => AppError(
message: "Error saving user",
type: AppErrorType.DatabaseError,
exception: error as Exception?,
),
);
}
// Optional: Begrüßungsnachricht senden
TaskEither<AppError, bool> sendWelcomeEmail(String email) {
return TaskEither.tryCatch(
() async {
print("Welcome email sent to $email");
return true;
},
(error, _) => AppError(
message: "Error sending welcome email",
type: AppErrorType.NetworkError,
exception: error as Exception?,
),
);
}