Created
May 27, 2020 14:58
-
-
Save calexandrepcjr/2038955b477f933f18745ce4a07e19df to your computer and use it in GitHub Desktop.
An experiment with validations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Validator<A, B> { | |
private validationBlock?: () => Promise<void>; | |
public constructor( | |
private readonly value: A, | |
private result: B, | |
private isValid: boolean = true, | |
) {} | |
public map<C>(mapper: (value: A) => C): Validator<C, B> { | |
return new Validator( | |
// tslint:disable-next-line:no-object-literal-type-assertion | |
this.isValid ? mapper(this.value) : ({} as C), | |
this.result, | |
this.isValid, | |
); | |
} | |
public when( | |
condition: (value: A) => boolean, | |
execute?: (value: A) => B, | |
): Validator<A, B> { | |
this.isValid = this.isValid && condition(this.value); | |
if (!this.isValid) { | |
return this; | |
} | |
this.result = execute === undefined ? this.result : execute(this.value); | |
return this; | |
} | |
public whenValid(validBlock: (result: A) => Promise<void>): this { | |
if (this.isValid) { | |
this.validationBlock = async () => validBlock(this.value); | |
} | |
return this; | |
} | |
public whenValidSync(validBlock: (result: A) => void): this { | |
if (this.isValid) { | |
validBlock(this.value); | |
} | |
return this; | |
} | |
public whenInvalid(invalidBlock: (result: B) => Promise<void>): this { | |
if (!this.isValid) { | |
this.validationBlock = async () => invalidBlock(this.result); | |
} | |
return this; | |
} | |
public whenInvalidSync(invalidBlock: (result: B) => void): this { | |
if (!this.isValid) { | |
invalidBlock(this.result); | |
} | |
return this; | |
} | |
public async resolve(): Promise<void> { | |
if (this.validationBlock === undefined) { | |
return; | |
} | |
return this.validationBlock(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment