mirror of https://github.com/lukechilds/ow.git
Sam Verschueren
7 years ago
committed by
Sindre Sorhus
3 changed files with 33 additions and 26 deletions
@ -1,20 +1,32 @@ |
|||
import * as is from '@sindresorhus/is'; |
|||
|
|||
export type Validator = (value: any) => string | undefined; |
|||
export interface Validator<T> { |
|||
message: (value: T) => string; |
|||
validator: (value: T) => boolean; |
|||
} |
|||
|
|||
export interface Context { |
|||
validators: Validator[]; |
|||
validators: Validator<any>[]; |
|||
} |
|||
|
|||
export class Predicate { |
|||
export class Predicate<T = any> { |
|||
constructor( |
|||
type: string, |
|||
public context: Context = { validators: [] } |
|||
private context: Context = { validators: [] } |
|||
) { |
|||
this.context.validators.push(value => { |
|||
if (!is[type](value)) { |
|||
return `Expected argument to be of type \`${type}\` but received type \`${is(value)}\``; |
|||
} |
|||
this.addValidator({ |
|||
message: value => `Expected argument to be of type \`${type}\` but received type \`${is(value)}\``, |
|||
validator: value => is[type](value) |
|||
}); |
|||
} |
|||
|
|||
get validators() { |
|||
return this.context.validators; |
|||
} |
|||
|
|||
protected addValidator(validator: Validator<T>) { |
|||
this.context.validators.push(validator); |
|||
|
|||
return this; |
|||
} |
|||
} |
|||
|
Loading…
Reference in new issue