$mol_data
Defines static typed DTO with strict runtime validation and user friendly error messages like:
["friends"][0]["phone"] undefined is not any of variants
undefined is not a string
undefined is not a number
Usage examples
Entities
const PersonDTO = $mol_data_record({
name : $mol_data_string ,
age : $mol_data_optional( $mol_data_integer ) ,
birthday : $mol_data_pipe( $mol_data_string , $mol_time_moment ) ,
})
const UserDTO = $mol_data_record({
... PersonDTO.config,
phone: $mol_data_variant( $mol_data_string , $mol_data_integer ),
mail: $mol_data_email,
})
const jin = UserDTO({
name : 'Jin' ,
age : 33 ,
birthday : '1984-08-04T12:00:00Z' ,
phone : 791234567890,
mail : 'foo@example.org' ,
})
function printName( user : typeof UserDTO.Value ) {
console.log( user.name )
}
printName( jin )
const json = {
name : 'Jin' ,
age : 33 ,
birthday : '1984-08-04T12:00:00Z' ,
phone : 791234567890,
mail : '</script>' ,
} as any
printName( UserDTO( json ) )
Units
const Weight = $mol_data_nominal({ Weight : $mol_data_integer })
const Length = $mol_data_nominal({ Length : $mol_data_integer })
let len = Length(10)
len = Length(20)
len = 20 as typeof Length.Value
len = 20
len = Weight(20)
len = Length( 20.1 )
(De)Serialization
const Duration = $mol_data_pipe(
$mol_data_variant(
$mol_data_string ,
$mol_data_integer ,
) ,
$mol_time_duration ,
)
JSON.stringify( Duration( 'P1D' ) )
JSON.stringify( Duration( 1000 ) )
Usage from NPM
npm install mol_data_all
import {
$mol_data_nominal as Nominal,
$mol_data_integer as Integer,
} from "mol_data_all"
const Int = Nominal({ Int: Integer })
const i = Int(1)
const j: typeof Int.Value = Int( i + 1 )
More complex example.
Similar projects