import * as http from "http" ; import * as https from "https" ; import { BufferUtil } from "./buffer-util" ; export class HTTPClient { public postWithExtraHeaders ( host , port , path , data , extraHeaders , callback ? ) { let post_options = { agent : false , host : host , port : port , path : path , method : "POST" , headers : { "Content-Type" : "application/json" , "Content-Length" : Buffer . byteLength ( data ) } } ; post_options . headers = Object . assign ( { } , post_options . headers , extraHeaders ) ; const functionCallback = function ( response ) { response . on ( "data" , function ( chunk ) { responseData = Buffer . concat ( [ responseData , chunk ] ) ; } ) ; response . on ( "end" , function ( ) { if ( callback !== undefined && callback !== null ) { callback ( responseData , response . statusCode , true ) ; } } ) ; } ; let responseData = Buffer . from ( "" ) ; let post_req = port === 443 ? https . request ( post_options , functionCallback ) : http . request ( post_options , functionCallback ) ; post_req . on ( "error" , function ( error ) { if ( callback !== undefined && callback !== null ) { callback ( BufferUtil . fromString ( error . message ) , 0 , false ) ; } } ) ; post_req . write ( data ) ; post_req . end ( ) ; } public post ( host , port , path , data , callback ? ) { this . postWithExtraHeaders ( host , port , path , data , { } , callback ) ; } public get ( host , port , path , callback ? ) { let options = { host : host , port : port , path : path , method : "GET" } ; let responseData = Buffer . from ( "" ) ; let request = http . request ( options , function ( response ) { response . on ( "data" , function ( chunk ) { responseData = Buffer . concat ( [ responseData , chunk ] ) ; } ) ; response . on ( "end" , function ( ) { if ( callback !== undefined && callback !== null ) { callback ( responseData , response . statusCode ) ; } } ) ; } ) ; request . end ( ) ; } }