@auth0/nextjs-auth0
Version:
Auth0 Next.js SDK
64 lines (63 loc) • 3.19 kB
JavaScript
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _GenericRequestCache_cache;
import { getScopeForAudience } from "../utils/scope-helpers.js";
/**
* A generic cache to manage in-flight requests to prevent duplicate requests.
* This ensures that multiple simultaneous requests for the same resource
* (based on a generated cache key) will share the same promise and result.
*/
export class GenericRequestCache {
constructor() {
_GenericRequestCache_cache.set(this, new Map());
}
/**
* Executes a request, caching the promise to prevent duplicate requests.
* @param requestHandler Function that performs the request and returns a promise.
* @param options Options used to generate the cache key.
* @returns A promise that resolves to the token response.
*/
async execute(requestHandler, options) {
// Generate a cache key based on audience and scope
const cacheKey = this.getTokenCacheKey(options);
// See if we have an in-flight request for this key
const inFlightRequest = __classPrivateFieldGet(this, _GenericRequestCache_cache, "f").get(cacheKey);
// If we have an in-flight request for this key,
// return the existing promise to prevent duplicate requests.
if (inFlightRequest) {
return inFlightRequest;
}
// Create and cache the promise for this request
const requestPromise = requestHandler().finally(() => {
// Clean up the cache when the request completes (success or failure)
__classPrivateFieldGet(this, _GenericRequestCache_cache, "f").delete(cacheKey);
});
// Store the in-flight request in the cache
__classPrivateFieldGet(this, _GenericRequestCache_cache, "f").set(cacheKey, requestPromise);
return requestPromise;
}
}
_GenericRequestCache_cache = new WeakMap();
/**
* A cache to manage in-flight token requests to prevent race conditions.
* This ensures that multiple simultaneous requests for the same token
* (based on audience and scope) will share the same promise and result.
*/
export class TokenRequestCache extends GenericRequestCache {
/**
* Generates a cache key for token requests based on audience and scope.
* @param options The options containing audience and scope
* @returns A unique cache key string
*/
getTokenCacheKey({ options, authorizationParameters }) {
const audience = options.audience ?? authorizationParameters?.audience ?? "";
const scope = options.scope ??
(authorizationParameters?.scope &&
getScopeForAudience(authorizationParameters?.scope, audience)) ??
"";
return `${audience}:${scope}`;
}
}