I have two validation functions for different values that return Either
. I'd like to throw an exception if one of them has a left
value and do nothing if both are right
. I've never used fp-ts before and can't figure out how to properly combine left results. My current solution works but does not feel like i'm using it properly.
import { Either, left, right, isLeft, getOrElse } from 'fp-ts/lib/Either';
function validateMonth( m: Month ): Either<Error, Month> {
return m.isInRange() ? right(m) : left(new Error('Month must be in range!'));
}
function validateYear( y: Year ): Either<Error, Year> {
return year.isBefore(2038) ? right(y) : left(new Error('Year must be before 2038!'));
}
function throwingValidator(m: Month, y: Year): void {
// todo: Refactor to get rid of intermediate variables,
// combining results of validateMonth and validateYear into a type
// of Either<Error, Unit>
const monthResult = validateMonth( month );
const yearResult = validateYear( year );
const throwOnError = (e: Error) => { throw e; };
if ( isLeft( monthResult ) ) { getOrElse(throwOnError)(monthResult); }
if ( isLeft( yearResult ) ) { getOrElse(throwOnError)(yearResult); }
}
I've read the introduction at https://dev.to/gcanti/getting-started-with-fp-ts-either-vs-validation-5eja but that code is exactly the opposite of what I want: I don't care about the input value after the validation and want to return only the first error that occurs.