Skip to content

Instantly share code, notes, and snippets.

@calexandrepcjr
Created May 27, 2020 14:58
Show Gist options
  • Save calexandrepcjr/2038955b477f933f18745ce4a07e19df to your computer and use it in GitHub Desktop.
Save calexandrepcjr/2038955b477f933f18745ce4a07e19df to your computer and use it in GitHub Desktop.
An experiment with validations
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