2929 * @property {Array<(body: any, headers?: RequestHeaders) => any?> } [transformRequest] An array of transformations to apply to the outgoing request
3030 * @property {string } [baseURL] a base URL from which to resolve all URLs
3131 * @property {typeof window.fetch } [fetch] Custom window.fetch implementation
32+ * @property {AbortSignal } [cancelToken] signal returned by AbortController
3233 * @property {any } [data]
3334 */
3435
6465 * @type {<T=any>(url: string, body?: any, config?: Options) => Promise<Response<T>> }
6566 */
6667
68+ /**
69+ * @typedef CancelToken
70+ * @type {{ (executor: Function): AbortSignal; source(): { token: AbortSignal; cancel: () => void; }; } }
71+ */
72+
73+ /**
74+ * @typedef CancelTokenSourceMethod
75+ * @type {() => { token: AbortSignal, cancel: () => void } }
76+ */
77+
6778/**
6879 * @public
6980 * @param {Options } [defaults = {}]
@@ -138,6 +149,37 @@ function create(defaults) {
138149 return out ;
139150 }
140151
152+ /**
153+ * CancelToken
154+ * @private
155+ * @param {Function } executor
156+ * @returns {AbortSignal }
157+ */
158+ function CancelToken ( executor ) {
159+ if ( typeof executor !== 'function' ) {
160+ throw new TypeError ( 'executor must be a function.' ) ;
161+ }
162+
163+ const ac = new AbortController ( ) ;
164+ executor ( ac . abort . bind ( ac ) ) ;
165+
166+ return ac . signal ;
167+ }
168+
169+ /**
170+ * @private
171+ * @type {CancelTokenSourceMethod }
172+ * @returns
173+ */
174+ CancelToken . source = ( ) => {
175+ const ac = new AbortController ( ) ;
176+
177+ return {
178+ token : ac . signal ,
179+ cancel : ac . abort . bind ( ac )
180+ } ;
181+ } ;
182+
141183 /**
142184 * Issues a request.
143185 * @public
@@ -199,7 +241,8 @@ function create(defaults) {
199241 method : ( _method || options . method || 'get' ) . toUpperCase ( ) ,
200242 body : data ,
201243 headers : deepMerge ( options . headers , customHeaders , true ) ,
202- credentials : options . withCredentials ? 'include' : _undefined
244+ credentials : options . withCredentials ? 'include' : _undefined ,
245+ signal : options . cancelToken
203246 } ) . then ( ( res ) => {
204247 for ( const i in res ) {
205248 if ( typeof res [ i ] != 'function' ) response [ i ] = res [ i ] ;
@@ -226,9 +269,16 @@ function create(defaults) {
226269
227270 /**
228271 * @public
229- * @type {AbortController }
272+ * @type {CancelToken }
273+ */
274+ redaxios . CancelToken = CancelToken ;
275+
276+ /**
277+ * @public
278+ * @param {DOMError } e
279+ * @returns {boolean }
230280 */
231- redaxios . CancelToken = /** @type { any } */ ( typeof AbortController == 'function' ? AbortController : Object ) ;
281+ redaxios . isCancel = ( e ) => e . name === 'AbortError' ;
232282
233283 /**
234284 * @public
0 commit comments