Skip to content

Commit 145f4a3

Browse files
committed
set cache headers
1 parent 8b206fe commit 145f4a3

File tree

6 files changed

+53
-19
lines changed

6 files changed

+53
-19
lines changed

index.mjs

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,6 @@ async function graphqlHandler(request, env, ctx) {
6464
);
6565
}
6666

67-
// default headers
68-
const responseOptions = {
69-
headers: {
70-
'Content-Type': 'application/json',
71-
}
72-
};
73-
7467
if (!dataAPI) {
7568
dataAPI = new DataSource(env);
7669
}
@@ -95,9 +88,13 @@ async function graphqlHandler(request, env, ctx) {
9588
const cachedResponse = await cacheMachine.get(env, {key});
9689
if (cachedResponse) {
9790
// Construct a new response with the cached data
98-
const newResponse = new Response(cachedResponse, responseOptions);
99-
// Add a custom 'X-CACHE: HIT' header so we know the request hit the cache
100-
newResponse.headers.append('X-CACHE', 'HIT');
91+
const newResponse = new Response(await cachedResponse.json(), {
92+
headers: {
93+
'Content-Type': 'application/json',
94+
'X-CACHE': 'HIT', // we know request hit the cache
95+
'Cache-Control': `public, max-age=${cachedResponse.headers.get('X-Cache-Ttl')}`,
96+
},
97+
});
10198
console.log('Request served from cache');
10299
// Return the new cached response
103100
return newResponse;
@@ -133,7 +130,15 @@ async function graphqlHandler(request, env, ctx) {
133130
throw new Error(`${originResponse.status} ${await originResponse.text()}`);
134131
}
135132
console.log('Request served from origin server');
136-
return new Response(originResponse.body, responseOptions);
133+
const newResponse = new Response(originResponse.body, {
134+
headers: {
135+
'Content-Type': 'application/json',
136+
},
137+
});
138+
if (originResponse.headers.has('X-Cache-Ttl')) {
139+
newResponse.headers.set('Cache-Control', `public, max-age=${originResponse.headers.get('X-Cache-Ttl')}`);
140+
}
141+
return newResponse;
137142
} catch (error) {
138143
console.error(`Error getting response from origin server: ${error}`);
139144
}
@@ -181,7 +186,14 @@ async function graphqlHandler(request, env, ctx) {
181186

182187
const body = JSON.stringify(result);
183188

184-
const response = new Response(body, responseOptions);
189+
const response = new Response(body, {
190+
headers: {
191+
'Content-Type': 'application/json',
192+
},
193+
});
194+
if (ttl > 0) {
195+
response.headers.set('Cache-Control', `public, max-age=${ttl}`);
196+
}
185197

186198
if (env.SKIP_CACHE !== 'true' && ttl > 0) {
187199
key = key ?? await cacheMachine.createKey(env, query, variables, specialCache);

plugins/plugin-graphql-origin.mjs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,11 @@ export default function useGraphQLOrigin(env) {
2424
throw new Error(`${queryResult.status} ${queryResult.statusText}: ${await queryResult.text()}`);
2525
}
2626
console.log('Request served from origin server');
27-
setResult(await queryResult.json());
2827
request.cached = true;
28+
if (queryResult.headers.has('X-Cache-Ttl')) {
29+
request.resultTtl = queryResult.headers.get('X-Cache-Ttl');
30+
}
31+
setResult(await queryResult.json());
2932
} catch (error) {
3033
console.error(`Error getting response from origin server: ${error}`);
3134
}

plugins/plugin-lite-api.mjs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,10 @@ export async function getLiteApiResponse(request, url, env, serverContext) {
5555
request.cached = true;
5656
// Construct a new response with the cached data
5757

58-
return new Response(cachedResponse, {
58+
return new Response(await cachedResponse.json(), {
5959
headers: {
6060
'X-CACHE': 'HIT',
61+
'Cache-Control': `public, max-age=${cachedResponse.headers.get('X-Cache-Ttl')}`,
6162
}
6263
});
6364
} else {
@@ -187,6 +188,10 @@ export async function getLiteApiResponse(request, url, env, serverContext) {
187188
});
188189
}
189190
const responseBody = JSON.stringify(items ?? [], null, 4);
191+
192+
if (ttl > 0) {
193+
responseOptions.headers['Cache-Control'] = `public, max-age=${ttl}`;
194+
}
190195

191196
// Update the cache with the results of the query
192197
if (env.SKIP_CACHE !== 'true' && ttl > 0) {

plugins/plugin-nightbot.mjs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,10 @@ export async function getNightbotResponse(request, url, env, serverContext) {
4444
if (cachedResponse) {
4545
console.log(`Request served from cache: ${new Date() - requestStart} ms`);
4646
request.cached = true;
47-
return new Response(cachedResponse, {
47+
return new Response(await cachedResponse.json(), {
4848
headers: {
4949
'X-CACHE': 'HIT',
50+
'Cache-Control': `public, max-age=${cachedResponse.headers.get('X-Cache-Ttl')}`,
5051
}
5152
});
5253
} else {
@@ -99,6 +100,11 @@ export async function getNightbotResponse(request, url, env, serverContext) {
99100
} finally {
100101
data.clearRequestData(context.requestId);
101102
}
103+
104+
const headers = {};
105+
if (ttl > 0) {
106+
headers['Cache-Control'] = `public, max-age=${ttl}`;
107+
}
102108

103109
// Update the cache with the results of the query
104110
if (env.SKIP_CACHE !== 'true' && ttl > 0) {
@@ -110,7 +116,9 @@ export async function getNightbotResponse(request, url, env, serverContext) {
110116
serverContext.waitUntil(putCachePromise);
111117
}
112118
}
113-
return new Response(responseBody)
119+
return new Response(responseBody, {
120+
headers,
121+
});
114122
}
115123

116124
export default function useNightbot(env) {

plugins/plugin-use-cache-machine.mjs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ export default function useCacheMachine(env) {
2626
if (cachedResponse) {
2727
console.log('Request served from cache');
2828
request.cached = true;
29-
setResult(JSON.parse(cachedResponse));
29+
request.resultTtl = cachedResponse.headers.get('X-Cache-Ttl');
30+
setResult(JSON.parse(await cachedResponse.json()));
3031
}
3132
},
3233
onValidate({ context, extendContext, params, validateFn, addValidationRule, setValidationFn, setResult }) {
@@ -98,6 +99,7 @@ export default function useCacheMachine(env) {
9899
ttl = 1800;
99100
}
100101
if (env.SKIP_CACHE !== 'true' && ttl > 0 && env.USE_ORIGIN !== 'true') {
102+
request.resultTtl = String(ttl);
101103
// using waitUntil doesn't hold up returning a response but keeps the worker alive as long as needed
102104
const cacheBody = JSON.stringify(result);
103105
if (cacheBody.length > 0) {
@@ -120,6 +122,10 @@ export default function useCacheMachine(env) {
120122
if (request.data && request.requestId) {
121123
request.data.clearRequestData(request.requestId);
122124
}
125+
if (request.resultTtl) {
126+
response.headers.set('X-Cache-Ttl', request.resultTtl);
127+
response.headers.set('Cache-Control', `public, max-age=${request.resultTtl}`);
128+
}
123129
setCors(response);
124130
},
125131
}

utils/cache-machine.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ const cacheMachine = {
8181
});
8282
cacheFailCount = 0;
8383
if (response.status === 200) {
84-
return await response.json();
84+
return response;
8585
} else if (response.status !== 404) {
8686
console.error(`failed to read from cache: ${response.status}`);
8787
}
@@ -132,7 +132,7 @@ const cacheMachine = {
132132
'content-type': 'application/json;charset=UTF-8',
133133
'Authorization': `Basic ${env.CACHE_BASIC_AUTH}`
134134
},
135-
timeout: 10000,
135+
timeout: 20000,
136136
});
137137
console.log('Response cached');
138138
response.body.cancel();

0 commit comments

Comments
 (0)