Skip to content

Commit

Permalink
Abort in-flight requests if new request is executed (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
pijng authored Jan 7, 2025
1 parent 9b914e7 commit 0d3c004
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions web/src/shared/api/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type BaseResponse = {
};

const BASE_URL = process.env.NODE_ENV === "development" ? "//127.0.0.1:4200" : "";
const abortControllers = new Map<string, AbortController>();

export const baseRequest = async ({
token,
Expand All @@ -30,12 +31,18 @@ export const baseRequest = async ({
headers?: HeadersInit;
}) => {
try {
abortControllers.get(url)?.abort();
const controller = new AbortController();
const { signal } = controller;
abortControllers.set(url, controller);

const response = await fetch(`${BASE_URL}${url}`, {
method,
credentials: "include",
referrerPolicy: "origin",
body,
headers: { ...headers, "Content-Type": "application/json", Authorization: `Bearer ${token}` },
signal,
});

const responseText = await response.clone().text();
Expand All @@ -57,6 +64,8 @@ export const baseRequest = async ({
return jsonResponse;
} catch (error) {
console.log(error);
} finally {
abortControllers.delete(url);
}
};

Expand Down

0 comments on commit 0d3c004

Please # to comment.