Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use AbortController, fix multipart boundary #21

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 69 additions & 30 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,46 +11,77 @@ import { isUndefined, isStandardBrowserEnv, isFormData } from 'axios/lib/utils';
*/
export default async function fetchAdapter(config) {
const request = createRequest(config);
const promiseChain = [getResponse(request, config)];

if (config.timeout && config.timeout > 0) {
promiseChain.push(
new Promise((res) => {
setTimeout(() => {
const message = config.timeoutErrorMessage
? config.timeoutErrorMessage
: 'timeout of ' + config.timeout + 'ms exceeded';
res(createError(message, config, 'ECONNABORTED', request));
}, config.timeout);
})
);
const stageOne = await startFetch(request, config);
const data = getResponse(stageOne)
const theSettle = config.settle instanceof Function
? config.settle
: settle;
return new Promise((resolve, reject) => {
theSettle(resolve, reject, data);
})
}

async function startFetch(request, config) {
const createNetworkError = () => {
const networkError = createError('Network Error', config, 'ERR_NETWORK', request);
return networkError;
}

const data = await Promise.race(promiseChain);
return new Promise((resolve, reject) => {
if (data instanceof Error) {
reject(data);
} else {
Object.prototype.toString.call(config.settle) === '[object Function]'
? config.settle(resolve, reject, data)
: settle(resolve, reject, data);
if (typeof config.time !== 'number' || isNaN(config.time) || config.time <= 0) {
try {
return await fetch(request);
} catch {
throw createNetworkError();
}
}

const createTimeoutError = () => {
const message = config.timeoutErrorMessage
? config.timeoutErrorMessage
: 'timeout of ' + config.timeout + 'ms exceeded';
const timeoutError = createError(message, config, 'ECONNABORTED', request);
return timeoutError;
};

try {
var abortController = new AbortController()
} catch (error) {
return new Promise(async(resolve, reject) => {
setTimeout(() => {
reject(createTimeoutError())
}, time);

try {
resolve(await fetch(request));
} catch (error) {
reject(createNetworkError());
}
})
}

setTimeout(() => {
abortController.abort()
}, config.timeout);

try {
return await fetch(request, {
signal: abortController.signal
});
} catch (error) {
if (abortController.signal.aborted) {
throw createTimeoutError();
}
});

throw createNetworkError();
}
}


/**
* Fetch API stage two is to get response body. This funtion tries to retrieve
* response body based on response's type
*/
async function getResponse(request, config) {
let stageOne;
try {
stageOne = await fetch(request);
} catch (e) {
return createError('Network Error', config, 'ERR_NETWORK', request);
}

async function getResponse(stageOne, config) {
const response = {
ok: stageOne.ok,
status: stageOne.status,
Expand Down Expand Up @@ -87,6 +118,14 @@ async function getResponse(request, config) {
* This function will create a Request object based on configuration's axios
*/
function createRequest(config) {
// Fix bug https://stackoverflow.com/questions/39280438/fetch-missing-boundary-in-multipart-form-data-post
if (config.data instanceof FormData && config.headers) {
const ContentType = 'Content-Type';
delete config.headers[ContentType];
delete config.headers[ContentType.toLowerCase()];
delete config.headers[ContentType.toUpperCase()];
}

Comment on lines +121 to +128
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need this. There's code to do it later in the code. Your use case seems similar to mine, which is run axios on a ServiceWorker. I think we just need to fix the condition in the code a little bit below to make sure it enters there. It's not entering the if condition in case of ServiceWorkers because isStandardBrowserEnv is returning false as ServiceWorkers don't have access to window nor document.

const headers = new Headers(config.headers);

// HTTP basic authentication
Expand Down