Skip to content

Commit 99db606

Browse files
committed
Fixed Cache Issue
1 parent e157ad4 commit 99db606

File tree

2 files changed

+42
-42
lines changed

2 files changed

+42
-42
lines changed

src/cdn-adapters/cloudflare/cloudflareAdapter.js

Lines changed: 40 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ class CloudflareAdapter {
238238
if (this.cookiesToSetRequest.length > 0) {
239239
newRequest = this.setMultipleReqSerializedCookies(newRequest, this.cookiesToSetRequest);
240240
}
241-
241+
242242
// Add additional headers from cdnSettings if present
243243
if (cdnSettings.additionalHeaders && typeof cdnSettings.additionalHeaders === 'object') {
244244
this.logger.debug('Adding additional headers from cdnSettings');
@@ -320,9 +320,12 @@ class CloudflareAdapter {
320320
*/
321321
async handleFetchFromOrigin(request, originUrl, cdnSettings, ctx) {
322322
this.logger.debug(`Handling fetch from origin [handleFetchFromOrigin]: ${originUrl}`);
323-
let response = undefined;
324-
let cacheKey = undefined;
323+
let response;
324+
let cacheKey;
325325
const clonedRequest = this.cloneRequestWithNewUrl(request, originUrl);
326+
const shouldUseCache =
327+
this.coreLogic.requestConfig?.overrideCache !== true && cdnSettings?.cacheRequestToOrigin === true;
328+
326329
this.eventListenersResult = await this.eventListeners.trigger('beforeCreateCacheKey', request, this.result);
327330
if (this.eventListenersResult && this.eventListenersResult.cacheKey) {
328331
cacheKey = this.eventListenersResult.cacheKey;
@@ -331,16 +334,36 @@ class CloudflareAdapter {
331334
this.eventListenersResult = await this.eventListeners.trigger('afterCreateCacheKey', cacheKey, this.result);
332335
}
333336
this.logger.debug(`Generated cache key: ${cacheKey}`);
337+
334338
const cache = caches.default;
335339
this.eventListenersResult = await this.eventListeners.trigger(
336340
'beforeReadingCache',
337341
request,
338342
this.requestConfig,
339343
this.result
340344
);
341-
if ((this.coreLogic.requestConfig?.overrideCache === true) && cdnSettings?.cacheRequestToOrigin === true) {
345+
346+
if (shouldUseCache) {
342347
response = await cache.match(cacheKey);
348+
this.logger.debug(`Cache ${response ? 'hit' : 'miss'} for key: ${cacheKey}`);
349+
}
350+
351+
if (!response) {
352+
this.logger.debug(`Fetching fresh content from origin: ${originUrl}`);
353+
const newRequest = this.abstractionHelper.abstractRequest.createNewRequestFromUrl(originUrl, clonedRequest);
354+
response = await this.fetchFromOriginOrCDN(newRequest);
355+
356+
if (shouldUseCache && response.ok) {
357+
// Only cache the response if caching is enabled and the response is successful
358+
response = this.abstractionHelper.abstractResponse.createNewResponse(response.body, response);
359+
if (!response.headers.has('Cache-Control')) {
360+
response.headers.set('Cache-Control', 'public');
361+
}
362+
await this.cacheResponse(ctx, cache, cacheKey, response, cdnSettings.cacheTTL);
363+
this.logger.debug(`Cached fresh content for key: ${cacheKey}`);
364+
}
343365
}
366+
344367
this.eventListenersResult = await this.eventListeners.trigger(
345368
'afterReadingCache',
346369
request,
@@ -352,30 +375,6 @@ class CloudflareAdapter {
352375
response = this.eventListenersResult.modifiedResponse;
353376
}
354377

355-
if (!response) {
356-
this.logger.debug(`Cache miss for ${originUrl}. Fetching from origin.`);
357-
const newRequest = this.abstractionHelper.abstractRequest.createNewRequestFromUrl(originUrl, clonedRequest);
358-
response = await this.fetchFromOriginOrCDN(newRequest);
359-
if (response.headers.has('Cache-Control')) {
360-
response = this.abstractionHelper.abstractResponse.createNewResponse(response.body, response);
361-
response.headers.set('Cache-Control', 'public');
362-
}
363-
if (response.ok) {
364-
this.cacheResponse(ctx, cache, cacheKey, response, cdnSettings.cacheTTL = null);
365-
this.eventListenersResult = await this.eventListeners.trigger(
366-
'afterCacheResponse',
367-
request,
368-
response,
369-
this.result
370-
);
371-
if (this.eventListenersResult && this.eventListenersResult.modifiedResponse) {
372-
response = this.eventListenersResult.modifiedResponse;
373-
}
374-
}
375-
} else {
376-
this.logger.debug(`Cache hit for: ${originUrl} with cacheKey: ${cacheKey}`);
377-
}
378-
379378
return this.applyResponseSettings(response, cdnSettings);
380379
}
381380

@@ -435,28 +434,28 @@ class CloudflareAdapter {
435434
try {
436435
let urlToFetch = typeof input === 'string' ? input : input.url;
437436
this.logger.debug('urlToFetch:', urlToFetch);
438-
437+
439438
// Parse the original URL
440439
const originalUrl = new URL(urlToFetch);
441-
440+
442441
// Check if the URL is for the Optimizely datafile
443442
if (!originalUrl.hostname.includes('cdn.optimizely.com')) {
444443
// Create a new URL using this.pagesUrl as the base
445444
const newUrl = new URL(this.pagesUrl);
446-
445+
447446
// Preserve the original path and search parameters
448447
newUrl.pathname = originalUrl.pathname;
449448
newUrl.search = originalUrl.search;
450-
449+
451450
urlToFetch = newUrl.toString();
452-
451+
453452
if (urlToFetch.endsWith('/')) {
454453
urlToFetch = urlToFetch.slice(0, -1);
455454
}
456455
}
457-
456+
458457
this.logger.debug(`Fetching from origin or CDN [fetchFromOriginOrCDN]: ${urlToFetch}`, options);
459-
458+
460459
const response = await AbstractRequest.fetchRequest(urlToFetch, options);
461460
this.logger.debug(`Fetching from origin or CDN [fetchFromOriginOrCDN] - response`, response);
462461
return response;
@@ -617,19 +616,19 @@ class CloudflareAdapter {
617616
async getDatafile(sdkKey, ttl = 3600) {
618617
this.logger.debugExt(`Getting datafile [getDatafile]: ${sdkKey}`);
619618
const url = `https://cdn.optimizely.com/datafiles/${sdkKey}.json`;
620-
619+
621620
try {
622-
const response = await this.fetchFromOriginOrCDN(url, {
621+
const response = await this.fetchFromOriginOrCDN(url, {
623622
cf: { cacheTtl: ttl },
624623
headers: {
625-
'Content-Type': 'application/json'
626-
}
624+
'Content-Type': 'application/json',
625+
},
627626
});
628-
627+
629628
if (!response.ok) {
630629
throw new Error(`Failed to fetch datafile: ${response.statusText}`);
631630
}
632-
631+
633632
return await response.text();
634633
} catch (error) {
635634
this.logger.error(`Error fetching datafile for SDK key ${sdkKey}: ${error}`);

src/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ let abstractionHelper, logger, abstractRequest, incomingRequest, environmentVari
4040
let optimizelyProvider, coreLogic, cdnAdapter;
4141

4242
// URL of your Pages deployment
43-
const PAGES_URL = 'https://edge-agent-demo.pages.dev/';
43+
// const PAGES_URL = 'https://edge-agent-demo.pages.dev/';
44+
const PAGES_URL = 'https://edge-agent-demo-simone-tutorial.pages.dev';
4445

4546
/**
4647
* Initializes the core logic of the application.

0 commit comments

Comments
 (0)