diff --git a/test/test.ts b/test/test.ts index 609e777..6bd7dcb 100644 --- a/test/test.ts +++ b/test/test.ts @@ -13,13 +13,18 @@ tap.test('should request a JSON document over https', async () => { .toEqual(1); }); -tap.skip.test('should post a JSON document over http', async () => { +tap.test('should post a JSON document over http', async () => { await expectAsync(smartrequest.postJson('http://md5.jsontest.com/?text=example_text')) .property('body') .property('md5') .toEqual('fa4c6baa0812e5b5c80ed8885e55a8a6'); }); +tap.test('should safe get stuff', async () => { + smartrequest.safeGet('http://coffee.link/'); + smartrequest.safeGet('https://coffee.link/'); +}); + tap.skip.test('should deal with unix socks', async () => { const socketResponse = await smartrequest.request( 'http://unix:/var/run/docker.sock:/containers/json', diff --git a/ts/00_commitinfo_data.ts b/ts/00_commitinfo_data.ts index 53ee69f..3204b83 100644 --- a/ts/00_commitinfo_data.ts +++ b/ts/00_commitinfo_data.ts @@ -3,6 +3,6 @@ */ export const commitinfo = { name: '@pushrocks/smartrequest', - version: '2.0.14', + version: '2.0.15', description: 'dropin replacement for request' } diff --git a/ts/smartrequest.interfaces.ts b/ts/smartrequest.interfaces.ts index 6ce2682..f0acf93 100644 --- a/ts/smartrequest.interfaces.ts +++ b/ts/smartrequest.interfaces.ts @@ -6,4 +6,5 @@ export interface ISmartRequestOptions extends https.RequestOptions { requestBody?: any; autoJsonParse?: boolean; queryParams?: { [key: string]: string }; + hardDataCuttingTimeout?: number; } diff --git a/ts/smartrequest.request.ts b/ts/smartrequest.request.ts index 510d0ff..83ff817 100644 --- a/ts/smartrequest.request.ts +++ b/ts/smartrequest.request.ts @@ -166,11 +166,18 @@ export let request = async ( } // lets perform the actual request - const requestToFire = requestModule.request(optionsArg, async (response) => { + const requestToFire = requestModule.request(optionsArg, async (resArg) => { + if (optionsArg.hardDataCuttingTimeout) { + setTimeout(() => { + resArg.destroy(); + done.reject(new Error('Request timed out')); + }, optionsArg.hardDataCuttingTimeout) + } + if (responseStreamArg) { - done.resolve(response as IExtendedIncomingMessage); + done.resolve(resArg as IExtendedIncomingMessage); } else { - const builtResponse = await buildUtf8Response(response, optionsArg.autoJsonParse); + const builtResponse = await buildUtf8Response(resArg, optionsArg.autoJsonParse); done.resolve(builtResponse); } }); @@ -209,12 +216,13 @@ export let request = async ( }; export const safeGet = async (urlArg: string) => { - const agentToUse = urlArg.startsWith('http') ? plugins.http.globalAgent : plugins.https.globalAgent; + const agentToUse = urlArg.startsWith('http://') ? new plugins.http.Agent() : new plugins.https.Agent(); try { const response = await request(urlArg, { method: 'GET', agent: agentToUse, timeout: 5000, + hardDataCuttingTimeout: 5000, autoJsonParse: false, }); return response;