import Ajv from 'ajv' ; import betterAjvErrors from 'better-ajv-errors' ; import { pathToRegexp } from 'path-to-regexp' ; import Glee from './glee.js' ; import { GleeFunctionEvent } from './index.js' ; import GleeMessage from './message.js' ; import Message from './message.js' ; interface IValidateDataReturn { errors ? : void | betterAjvErrors . IOutputError [ ] ; humanReadableError ? : void | betterAjvErrors . IOutputError [ ] ; isValid : boolean | PromiseLike < any > ; } private param { String } path param { String } channel export const getParams = ( path , channel ) : { [ key ] : string ; } | null => { if ( path === undefined ) return { } ; const keys = [ ] ; const re = pathToRegexp ( path , keys ) ; const result = re . exec ( channel ) ; if ( result === null ) return null ; return keys . map ( ( key , index ) => ( { [ key . name ] : result [ index + 1 ] } ) ) . reduce ( ( prev , val ) => ( { ... prev , ... val , } ) , { } ) ; } ; private param { GleeMessage } message return { GleeMessage } export const duplicateMessage = ( message ) : GleeMessage => { const newMessage = new Message ( { payload : message . payload , headers : message . headers , channel : message . channel , serverName : message . serverName , connection : message . connection , broadcast : message . broadcast , } ) ; if ( message . isInbound ( ) ) { newMessage . setInbound ( ) ; } else { newMessage . setOutbound ( ) ; } return newMessage ; } ; private param { String } path param { String } channel return { Boolean } export const matchChannel = ( path , channel ) : boolean => { return ( getParams ( path , channel ) !== null ) ; } ; private param { Any } data param { Object } schema returns export const validateData = ( data , schema ) : IValidateDataReturn => { const ajv = new Ajv ( { allErrors : true , jsonPointers : true } ) ; const validation = ajv . compile ( schema ) ; const isValid = validation ( data ) ; let errors ; let humanReadableError ; if ( ! isValid ) { humanReadableError = betterAjvErrors ( schema , data , validation . errors , { format : 'cli' , indent : 2 , } ) ; errors = betterAjvErrors ( schema , data , validation . errors , { format : 'js' , } ) ; } return { errors , humanReadableError , isValid , } ; } ; export const arrayHasDuplicates = ( array ) => { return ( new Set ( array ) ) . size !== array . length ; } ; export const gleeMessageToFunctionEvent = ( message , glee ) : GleeFunctionEvent => { return { payload : message . payload , headers : message . headers , channel : message . channel , connection : message . connection , serverName : message . serverName , glee , } as GleeFunctionEvent ; } ;