@@ -3,7 +3,6 @@ import { stringify } from 'querystring';
3
3
import merge from 'lodash.merge' ;
4
4
import http from 'http' ;
5
5
import https from 'https' ;
6
- import URL from 'url' ;
7
6
import { VetchError } from './types/vetchError' ;
8
7
import { Headers } from './interfaces/headers' ;
9
8
import { VetchResponse } from './interfaces/vetchResponse' ;
@@ -26,9 +25,20 @@ export class Vetch {
26
25
private async _defaultAdapter < T > (
27
26
opts : VetchOptions ,
28
27
) : Promise < VetchResponse < T > > {
29
- const res = await fetch ( opts . url , opts ) ;
30
- const data = await this . getResponseData ( opts , res ) ;
31
- return this . createResponse ( opts , res , data ) ;
28
+ const { timeout } = opts ;
29
+ let timeoutId = null ;
30
+ if ( timeout ) {
31
+ const controller = new AbortController ( ) ;
32
+ timeoutId = setTimeout ( ( ) => controller . abort ( ) , timeout ) ;
33
+ }
34
+
35
+ try {
36
+ const res = await fetch ( opts . url , opts ) ;
37
+ const data = await this . getResponseData ( opts , res ) ;
38
+ return this . createResponse ( opts , res , data ) ;
39
+ } finally {
40
+ clearTimeout ( timeoutId ) ;
41
+ }
32
42
}
33
43
34
44
async request < T > ( opts : VetchOptions = { } ) : Promise < VetchResponse < T > > {
@@ -116,10 +126,10 @@ export class Vetch {
116
126
117
127
// Allow a custom timeout to be used
118
128
const httpAgent = new http . Agent ( {
119
- timeout : this . defaults . timeout ,
129
+ timeout : opts . timeout ,
120
130
} ) ;
121
131
const httpsAgent = new https . Agent ( {
122
- timeout : this . defaults . timeout ,
132
+ timeout : opts . timeout ,
123
133
} ) ;
124
134
opts . agent = ( parsedUrl : URL ) : https . Agent | http . Agent => {
125
135
if ( parsedUrl . protocol === 'http:' ) {
0 commit comments