UNPKG

alova

Version:

The Request Toolkit For Ultimate Efficiency

100 lines (95 loc) 4.65 kB
/** * alova 3.5.0 (https://alova.js.org) * Document https://alova.js.org * Copyright 2026 Scott Hu. All Rights Reserved * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) */ 'use strict'; var shared = require('@alova/shared'); const isBodyData = (data) => shared.isString(data) || shared.isSpecialRequestBody(data); function adapterFetch(options = {}) { return (elements, method) => { const adapterConfig = method.config; const timeout = adapterConfig.timeout || 0; const ctrl = new AbortController(); const { data, headers } = elements; const isContentTypeSet = /content-type/i.test(shared.ObjectCls.keys(headers).join()); const isFormData = data && data.toString() === '[object FormData]'; // When the content type is not set and the data is not a form data object, the content type is set to application/json by default. if (!isContentTypeSet && !isFormData) { headers['Content-Type'] = 'application/json; charset=UTF-8'; } const ignoringHeaderValues = ['', shared.undefinedValue, shared.nullValue, shared.falseValue]; shared.ObjectCls.keys(headers).forEach(headerName => { // fetch headers do not allow setting undefined/null/false values if (shared.includes(ignoringHeaderValues, headers[headerName])) { shared.deleteAttr(headers, headerName); } }); const fetchPromise = (options.customFetch || fetch)(elements.url, { ...adapterConfig, method: elements.type, signal: ctrl.signal, body: isBodyData(data) ? data : shared.JSONStringify(data) }); // If the interruption time is set, the request will be interrupted after the specified time. let abortTimer; let isTimeout = shared.falseValue; if (timeout > 0) { abortTimer = shared.setTimeoutFn(() => { isTimeout = shared.trueValue; ctrl.abort(); }, timeout); } return { response: () => fetchPromise.then(response => { // Clear interrupt processing after successful request shared.clearTimeoutTimer(abortTimer); // Response's readable can only be read once and needs to be cloned before it can be reused. return response.clone(); }, err => shared.promiseReject(isTimeout ? shared.newInstance(Error, 'fetchError: network timeout') : err)), // The then in the Headers function needs to catch exceptions, otherwise the correct error object will not be obtained internally. headers: () => fetchPromise.then(({ headers: responseHeaders }) => responseHeaders, () => ({})), // Due to limitations of the node fetch library, this code cannot be unit tested, but it has passed the test in the browser. /* c8 ignore start */ onDownload: async (cb) => { let isAborted = shared.falseValue; const response = await fetchPromise.catch(() => { isAborted = shared.trueValue; }); if (!response) return; const { headers: responseHeaders, body } = response.clone(); const reader = body ? body.getReader() : shared.undefinedValue; const total = Number(responseHeaders.get('Content-Length') || responseHeaders.get('content-length') || 0); if (total <= 0) { return; } let loaded = 0; if (reader) { const pump = () => reader.read().then(({ done, value = new Uint8Array() }) => { if (done || isAborted) { isAborted && cb(loaded, 0); } else { loaded += value.byteLength; cb(loaded, total); return pump(); } }); pump(); } }, onUpload() { // eslint-disable-next-line no-console console.error("fetch API does'nt support uploading progress. please consider to change `@alova/adapter-xhr` or `@alova/adapter-axios`"); }, /* c8 ignore stop */ abort: () => { ctrl.abort(); shared.clearTimeoutTimer(abortTimer); } }; }; } module.exports = adapterFetch;