diff --git a/lib/src/verify.dart b/lib/src/verify.dart index caa76f6..5ef9be6 100644 --- a/lib/src/verify.dart +++ b/lib/src/verify.dart @@ -112,6 +112,26 @@ extension ValidatorUtils on ValidatorT { }; } + /// Transforms errors produced by the validor + // + /// Leaving the validation logic untouched. + /// returns validator with coerced output. + ValidatorT mapErrors(Function1 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) diff --git a/test/verify_test.dart b/test/verify_test.dart index 9e4974c..a44ab70 100644 --- a/test/verify_test.dart +++ b/test/verify_test.dart @@ -29,6 +29,20 @@ void main() { assert(error1 == error2); }); + test('can map errors', () { + const someUser = User('', '', null); + final Validator 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(someUser); + + assert(errors.length == 2); + }); + test('flatmap does not collect both validator errors', () { const someUser = User('', '', null); final error1 = Error('validation error');