Fix Beds24 token race condition.
Deduplicate in-flight /authentication/token requests per house so that concurrent page loads do not each trigger a separate token refresh, which was exhausting the Beds24 rate limit on first load. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
2b24334bfa
commit
74592a9e14
@@ -64,6 +64,7 @@ function getRefreshToken(houseId: string): string | undefined {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const accessTokenCache = new Map<string, { token: string; expiresAt: number }>();
|
const accessTokenCache = new Map<string, { token: string; expiresAt: number }>();
|
||||||
|
const pendingTokenRequests = new Map<string, Promise<string>>();
|
||||||
|
|
||||||
async function getAccessToken(houseId: string): Promise<string> {
|
async function getAccessToken(houseId: string): Promise<string> {
|
||||||
const refreshToken = getRefreshToken(houseId);
|
const refreshToken = getRefreshToken(houseId);
|
||||||
@@ -78,6 +79,13 @@ async function getAccessToken(houseId: string): Promise<string> {
|
|||||||
return cached.token;
|
return cached.token;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const inFlight = pendingTokenRequests.get(houseId);
|
||||||
|
if (inFlight) {
|
||||||
|
return inFlight;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenPromise = (async () => {
|
||||||
|
try {
|
||||||
const response = await fetch(`${BEDS24_API_BASE}/authentication/token`, {
|
const response = await fetch(`${BEDS24_API_BASE}/authentication/token`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: { refreshToken },
|
headers: { refreshToken },
|
||||||
@@ -98,6 +106,13 @@ async function getAccessToken(houseId: string): Promise<string> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return data.token;
|
return data.token;
|
||||||
|
} finally {
|
||||||
|
pendingTokenRequests.delete(houseId);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
pendingTokenRequests.set(houseId, tokenPromise);
|
||||||
|
return tokenPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function beds24Get<T>(
|
async function beds24Get<T>(
|
||||||
|
|||||||
Reference in New Issue
Block a user