Skip to content

Commit

Permalink
Add mapError
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielCardonaRojas committed Oct 11, 2023
1 parent 4e7170b commit f7059bc
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/src/verify.dart
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,26 @@ extension ValidatorUtils<S, T> on ValidatorT<S, T> {
};
}

/// Transforms errors produced by the validor
//
/// Leaving the validation logic untouched.
/// returns validator with coerced output.
ValidatorT<S, T> mapErrors<E>(Function1<dynamic, E?> transform) {
return (S input) {
final eitherErrorOrResult = this(input);
return eitherErrorOrResult.leftMap((errorList) {
return errorList.map((e) {
final newError = transform(e);
if (newError == null) {
return e;
}

return newError as dynamic;
}).toList();
});
};
}

/// Chains a validation to the output
///
/// Equivalent to flatMap((_) => validator)
Expand Down
14 changes: 14 additions & 0 deletions test/verify_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ void main() {
assert(error1 == error2);
});

test('can map errors', () {
const someUser = User('', '', null);
final Validator<User> validator =
(_) => const Left(['first error', 'second']);

final errors = validator.mapErrors((error) {
final errorMessage = error as String?;
if (errorMessage == null) return null;
return Error(errorMessage);
}).errors<Error>(someUser);

assert(errors.length == 2);
});

test('flatmap does not collect both validator errors', () {
const someUser = User('', '', null);
final error1 = Error('validation error');
Expand Down

0 comments on commit f7059bc

Please sign in to comment.