import ZSchema from 'shared/validate/z_schema' ; import Validator from 'z-schema' ; import { ResponseEntity } from 'shared/model/response' ; import { logger } from 'shared/util/logger' ; import { MESSAGE_CHANNEL } from 'shared/driver/socket/channels' ; import { ALL_SCHEMAS , MESSAGE } from 'shared/validate/schema/init' ; import { API_ACTION_TYPES } from 'shared/driver/socket/codes' ; import { Message , MessageType } from 'shared/model/message' ; /**
 * Compile all schemas for validate
 */ const validator = new ZSchema ( { noTypeless : true , noExtraKeywords : true , noEmptyArrays : true , noEmptyStrings : true } ) ; const isSchemasValid = validator . validateSchema ( ALL_SCHEMAS ) ; logger . debug ( '[API][SCHEMAS] VALID:' , isSchemasValid ) ; /**
 * Decorator for validate request
 */ export const validate = ( ) => { return function ( target , propertyName , descriptor ) { let descriptorFn = descriptor . value || descriptor . get ( ) ; return { value : ( message , socket ) : any => { let schemaID = message . code . toString ( ) ; if ( schemaID === API_ACTION_TYPES . CREATE_TRANSACTION && message . body && message . body . trs ) { schemaID = `CREATE_TRANSACTION.${ message . body . trs . type }` ; } if ( schemaID === API_ACTION_TYPES . CREATE_PREPARED_TRANSACTION && message . body ) { schemaID = `CREATE_PREPARED_TRANSACTION.${ message . body . type }` ; } validateData ( MESSAGE ( schemaID ) , message , ( err , isValid ) => { if ( ! isValid ) { message . body = new ResponseEntity ( { errors : [ `IS NOT VALID REQUEST:'${ message . code }'... ${ err . message }` ] } ) ; message . headers . type = MessageType . RESPONSE ; return handlerError . call ( this , message , socket ) ; } else { return descriptorFn . call ( this , message , socket ) ; } } ) ; } } ; } ; } ; export const validateData = ( schema , data , callback ) => { validator . validate ( data , schema , ( err , isValid ) => { if ( err ) { callback ( err [ 0 ] , isValid ) ; return ; } callback ( null , isValid ) ; } ) ; } ; const handlerError = ( message , socket ) => { logger . error ( `[Validation] ${ message . body . errors . join ( '. ' ) }` ) ; socket . emit ( MESSAGE_CHANNEL , message ) ; } ;