import * as http from 'http' ; import { httpHeaders } from '../../http' ; import Registry from '../../registry' ; import Handler from '../../handler' ; /** Abstract Handler for Updating mock state. */ abstract class UpdateMockHandler implements Handler { param registry param identifier param ngApimockId abstract handlePassThroughScenario ( registry , identifier , ngApimockId ? ) ; param registry param identifier param ngApimockId abstract handleScenarioSelection ( registry , identifier , scenario , ngApimockId ? ) ; param registry param identifier param echo param ngApimockId abstract handleEcho ( registry , identifier , echo , ngApimockId ? ) ; param registry param identifier param delay param ngApimockId abstract handleDelay ( registry , identifier , delay , ngApimockId ? ) ; inheritDoc handleRequest ( request , response , next , registry , ngApimockId ) { const requestDataChunks = [ ] ; request . on ( 'data' , ( rawData ) => { requestDataChunks . push ( rawData ) ; } ) ; request . on ( 'end' , ( ) => { const data = JSON . parse ( Buffer . concat ( requestDataChunks ) . toString ( ) ) ; try { const match = registry . mocks . filter ( _mock => _mock . identifier === data . identifier ) [ 0 ] ; if ( match !== undefined ) { if ( this . isScenarioSelectionRequest ( data ) ) { if ( this . isPassThroughScenario ( data . scenario ) ) { this . handlePassThroughScenario ( registry , data . identifier , ngApimockId ) ; } else if ( match . responses [ data . scenario ] ) { this . handleScenarioSelection ( registry , data . identifier , data . scenario , ngApimockId ) ; } else { throw new Error ( 'No scenario matching name [' + data . scenario + '] found' ) ; } } else if ( this . isEchoRequest ( data ) ) { this . handleEcho ( registry , data . identifier , data . echo , ngApimockId ) ; } else if ( this . isDelayResponseRequest ( data ) ) { this . handleDelay ( registry , data . identifier , data . delay , ngApimockId ) ; } } else { throw new Error ( 'No mock matching identifier [' + data . identifier + '] found' ) ; } response . writeHead ( 200 , httpHeaders . CONTENT_TYPE_APPLICATION_JSON ) ; response . end ( ) ; } catch ( e ) { response . writeHead ( 409 , httpHeaders . CONTENT_TYPE_APPLICATION_JSON ) ; response . end ( JSON . stringify ( e , [ 'message' ] ) ) ; } } ) ; } param data returns { boolean } private isScenarioSelectionRequest ( data ) { return data . scenario !== undefined ; } param data returns { boolean } private isEchoRequest ( data ) { return data . echo !== undefined ; } param data returns { boolean } private isDelayResponseRequest ( data ) { return data . delay !== undefined ; } param scenario returns { boolean } private isPassThroughScenario ( scenario ) { return scenario === null || scenario === 'passThrough' ; } } export default UpdateMockHandler ;