Skip to content

Commit

Permalink
fix: concurrency issues with async requests
Browse files Browse the repository at this point in the history
  • Loading branch information
katiestahl committed Sep 5, 2024
1 parent fcf4891 commit 8e1efb6
Show file tree
Hide file tree
Showing 2 changed files with 151 additions and 101 deletions.
41 changes: 41 additions & 0 deletions client/src/services/apiService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// a service layer for api requests that enables reusability of abort controllers
class ApiService {
private controllers: Map<string, AbortController>;

constructor() {
this.controllers = new Map();
}

public async makeRequest<T>(
key: string,
url: string,
options?: RequestInit
): Promise<T> {
if (this.controllers.has(key)) {
this.controllers.get(key)?.abort();
}

const controller = new AbortController();
this.controllers.set(key, controller);

try {
const response = await fetch(url, {
...options,
signal: controller.signal,
});

const data: T = await response.json();
return data;
} finally {
this.controllers.delete(key);
}
}

public cancelRequest(key: string) {
if (this.controllers.has(key)) {
this.controllers.get(key)?.abort();
}
}
}

export const apiService = new ApiService();
Loading

0 comments on commit 8e1efb6

Please sign in to comment.