import isPlainObj = require ( 'is-plain-obj' ) ; import * as url from 'url' ; import { ERRORS } from './errors' ; import { getInstance } from './logger' ; import { Filter , Options } from './types' ; const logger = getInstance ( ) ; export type Config = { context : Filter ; options : Options ; } ; export function createConfig ( context , opts ? ) { const config = { context : undefined , options : { } as Options , } ; if ( isContextless ( context , opts ) ) { config . context = '/' ; config . options = Object . assign ( config . options , context ) ; } else if ( isStringShortHand ( context ) ) { const oUrl = url . parse ( context ) ; const target = [ oUrl . protocol , '//' , oUrl . host ] . join ( '' ) ; config . context = oUrl . pathname || '/' ; config . options = Object . assign ( config . options , { target } , opts ) ; if ( oUrl . protocol === 'ws:' || oUrl . protocol === 'wss:' ) { config . options . ws = true ; } } else { config . context = context ; config . options = Object . assign ( config . options , opts ) ; } configureLogger ( config . options ) ; if ( ! config . options . target && ! config . options . router ) { throw new Error ( ERRORS . ERR_CONFIG_FACTORY_TARGET_MISSING ) ; } return config ; } example param { String } context return { Boolean } function isStringShortHand ( context ) { if ( typeof context === 'string' ) { return ! ! url . parse ( context ) . host ; } } example param { Object } context param { * } opts return { Boolean } function isContextless ( context , opts ) { return isPlainObj ( context ) && ( opts == null || Object . keys ( opts ) . length === 0 ) ; } function configureLogger ( options ) { if ( options . logLevel ) { logger . setLevel ( options . logLevel ) ; } if ( options . logProvider ) { logger . setProvider ( options . logProvider ) ; } }