import _ from 'ramda' ; import Checker from './check' ; import { Expect } from './check' ; class InputError extends Error { field : string ; status : number ; constructor ( field ) { super ( `incorrect field: '${ field }', please check again!` ) ; this . field = field ; this . status = 400 ; } } export interface ExpectObject { [ key ] : Expect ; } export interface Input { [ key ] : any ; } export default function ( rawInput , expect ) { const input = _ . clone ( rawInput ) ; Object . keys ( expect ) . forEach ( ( key ) => { if ( expect [ key ] === undefined ) { delete input [ key ] ; return ; } if ( ! Checker . required ( input [ key ] , expect [ key ] ) . is ) { throw new InputError ( key ) ; } const defaultVal = Checker . default ( input [ key ] , expect [ key ] ) . val ; if ( defaultVal !== undefined ) { input [ key ] = defaultVal ; } if ( input [ key ] === undefined ) return ; const { is , val } = Checker . check ( input [ key ] , expect [ key ] ) ; if ( ! is ) throw new InputError ( key ) ; input [ key ] = val ; } ) ; return input ; }