import Context from '../ctx' ; export const isAString = x => typeof x == 'string' ; export const isNotAString = x => ! isAString ( x ) ; /**
 * String
 */ export default class StringContext < Maybe extends null | undefined | string = string > extends Context < string | Maybe > { public readonly name = 'String' ; public enum : string [ ] | null = null ; public minLength : number | null = null ; public maxLength : number | null = null ; constructor ( optional = false , nullable = false ) { super ( optional , nullable ) ; this . push ( v => isNotAString ( v ) ? new Error ( 'must-be-a-string' ) : true ) ; this . push ( v => this . minLength != null ? v . length < this . minLength ? new Error ( 'invalid-range' ) : true : true , 'min' ) ; this . push ( v => this . maxLength != null ? v . length > this . maxLength ? new Error ( 'invalid-range' ) : true : true , 'max' ) ; this . push ( v => this . enum != null ? ! this . enum . some ( x => x === v ) ? new Error ( 'not-match-pattern' ) : true : true , 'enum' ) ; } param min param max public range ( min , max ) { this . min ( min ) ; this . max ( max ) ; return this ; } param threshold public min ( threshold ) { this . minLength = threshold ; return this ; } param threshold public max ( threshold ) { this . maxLength = threshold ; return this ; } param length public length ( length ) { this . min ( length ) ; this . max ( length ) ; return this ; } param pattern public or ( pattern ) { if ( typeof pattern == 'string' ) pattern = pattern . split ( '|' ) ; this . enum = pattern ; return this ; } param str public notInclude ( str ) { if ( typeof str == 'string' ) str = [ str ] ; this . push ( v => { const match = ( str as string [ ] ) . some ( x => v . indexOf ( x ) !== - 1 ) ; if ( match ) return new Error ( 'includes-forbidden-string' ) ; return true ; } , 'notInclude' ) ; return this ; } param pattern public match ( pattern ) { this . push ( v => ! pattern . test ( v ) ? new Error ( 'not-match-pattern' ) : true , 'match' ) ; return this ; } param pattern public notMatch ( pattern ) { this . push ( v => pattern . test ( v ) ? new Error ( 'match-pattern' ) : true , 'notMatch' ) ; return this ; } public makeOptional ( ) { return new StringContext ( true , false ) ; } public makeNullable ( ) { return new StringContext ( false , true ) ; } public makeOptionalNullable ( ) { return new StringContext ( true , true ) ; } }