-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: concurrency issues with async requests
- Loading branch information
1 parent
fcf4891
commit 8e1efb6
Showing
2 changed files
with
151 additions
and
101 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Oops, something went wrong.