For anyone else interested in this, I have now tested this and can confirm that the response from Service bindings can be cached. Here is my example:
workerA:
export default {
async fetch(request, env, ctx) {
const cache = caches.default;
let response = await cache.match(request);
let returnData = {
inCache: false,
addedToCache: false,
messages: [],
secondsLeftInCache: "0"
};
if (!response) {
returnData.messages.push(`Response for request url: ${request.url} not present in cache. Fetching and caching request.`);
response = await env.auth.fetch(request.clone());
//response = await fetch("https://example.com/");
if (response.status !== 200) {
returnData.messages.push(`Response for auth was not 200.`);
return new Response(JSON.stringify(returnData, null, 2));
}
response = new Response(response.body, response);
response.headers.set("Cache-Control", "s-maxage=20");
ctx.waitUntil(cache.put(request, response.clone()));
returnData.addedToCache = true;
} else {
returnData.inCache = true
returnData.messages.push(`Cache hit for: ${request.url}.`);
}
returnData.secondsLeftInCache = response.headers.get("Cache-Control")
return new Response(JSON.stringify(returnData, null, 2));
},
};
workerB:
export default {
async fetch(request) {
console.log('Requested');
/**
* @param {string} PRESHARED_AUTH_HEADER_KEY Custom header to check for key
* @param {string} PRESHARED_AUTH_HEADER_VALUE Hard coded key value
*/
const PRESHARED_AUTH_HEADER_KEY = "X-Custom-PSK";
const PRESHARED_AUTH_HEADER_VALUE = "mypresharedkey";
const psk = request.headers.get(PRESHARED_AUTH_HEADER_KEY);
if (psk === PRESHARED_AUTH_HEADER_VALUE) {
console.log('Authenticated')
// Correct preshared header key supplied. Fetch request from origin.
return new Response("All good", {
status: 200,
});
}
console.log('Not authenticated')
// Incorrect key supplied. Reject the request.
return new Response("Sorry, you have supplied an invalid key.", {
status: 403,
});
},
};
Set up the route so it doesnt use worker.dev (as cacheAPI cannot be used with worker.dev)
Set up binding between workerA and workerB
Send request with curl:
curl -H "X-Custom-PSK: mypresharedkey" https://yourDomain.com/testing/example
Response:
{
"inCache": false,
"addedToCache": true,
"messages": [
"Response for request url: https://yourDomain.com/testing/example not present in cache. Fetching and caching request."
],
"secondsLeftInCache": "s-maxage=20"
Responses after (although seems to take a about 5 cache missed before its added to cache):
{
"inCache": true,
"addedToCache": false,
"messages": [
"Cache hit for: https://yourDomain.com/testing/example."
],
"secondsLeftInCache": "max-age=14400, s-maxage=20"
}