Created
August 8, 2019 01:28
-
-
Save t81lal/dda96041cc2cced8e408314a698b4fa0 to your computer and use it in GitHub Desktop.
Two different ways to provide runtime type support for the username field
This file contains 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
import * as t from 'io-ts'; | |
import { withMessage } from 'io-ts-types/lib/withMessage'; | |
import { Either, either } from 'fp-ts/lib/Either'; | |
interface UsernameBrand { | |
readonly Username: unique symbol; | |
} | |
type ErrorOrString = Either<t.Errors, string> | |
export const Username2 = new t.Type<string, string, unknown>( | |
'Username2', | |
t.string.is, | |
( u, c ): ErrorOrString => | |
either.chain( t.string.validate( u, c ), ( s: string ): ErrorOrString => { | |
const length = s.length; | |
if( length <= 2 || length >= 16 ) { | |
return t.failure( u, c, 'Invalid length' ); | |
} else if( !/^[a-z0-9]+$/i.test( s ) ) { | |
return t.failure( u, c, 'Invalid characters' ); | |
} else { | |
return t.success( s ); | |
} | |
} ), | |
String | |
); | |
export const Username = withMessage( t.brand( | |
t.string, | |
( s ): s is t.Branded<string, UsernameBrand> => { | |
const length = s.length; | |
if( length <= 2 || length >= 16 ) { | |
return false; | |
} else { | |
return /^[a-z0-9]+$/i.test( s ); | |
} | |
}, | |
'Username', | |
), ( x ): string => 'Invalid username' ); | |
export type Username = t.TypeOf<typeof Username> | |
export type Username2 = t.TypeOf<typeof Username2> | |
export const LoginRequest = t.type( { | |
username: Username2, | |
password: t.string, | |
} ); | |
export type LoginRequest = t.TypeOf<typeof LoginRequest> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment