Last active
December 5, 2022 18:03
-
-
Save g3rv4/628e1c3cc472ea319f4e0112baecab0f to your computer and use it in GitHub Desktop.
CF worker to ignore requests that are not Follows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
// NOTE: can’t use fetch here, as we’re not in an async scope yet | |
event.respondWith(eventHandler(event)); | |
}); | |
async function eventHandler(event) { | |
const { headers } = event.request; | |
const contentType = headers.get('content-type') || ''; | |
if (event.request.method === 'POST' && contentType.indexOf('application/activity+json') >= 0) { | |
const json = await event.request.clone().json(); | |
if (json.type !== 'Follow') { | |
return new Response('{}', { | |
headers: { | |
'content-type': 'application/activity+json', | |
}, | |
}); | |
} | |
} | |
if (event.request.method === 'GET') { | |
// use the cache! | |
const cacheUrl = new URL(event.request.url); | |
const cacheKey = new Request(cacheUrl.toString(), event.request); | |
const cache = caches.default; | |
let response = await cache.match(cacheKey); | |
if (!response) { | |
response = await fetch(event.request, { cf: { resolveOverride: 'realorigin.gervas.io' } }); | |
response = new Response(response.body, response); | |
response.headers.append('Cache-Control', 's-maxage=600'); | |
event.waitUntil(cache.put(cacheKey, response.clone())); | |
} | |
return response; | |
} else { | |
return fetch(event.request, { cf: { resolveOverride: 'realorigin.gervas.io' } }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment