fix: analytics worker

This commit is contained in:
Cory Dransfeldt 2024-08-02 08:47:41 -07:00
parent 7e1be46b2e
commit e591a00888
No known key found for this signature in database
3 changed files with 19 additions and 14 deletions

View file

@ -1,7 +1,7 @@
const scriptName = '/js/script.js'
const endpoint = '/api/event'
addEventListener('fetch', event => {
addEventListener("fetch", (event) => {
event.passThroughOnException()
event.respondWith(handleRequest(event))
})
@ -10,8 +10,11 @@ async function handleRequest(event) {
const url = new URL(event.request.url)
const pathname = url.pathname
if (pathname === scriptName) getScript(event)
if (pathname === endpoint) return postData(event)
if (pathname === scriptName) {
return getScript(event)
} else if (pathname === endpoint) {
return postData(event)
}
return new Response(null, { status: 404 })
}
@ -20,10 +23,12 @@ async function getScript(event) {
let response = await cache.match(event.request)
if (!response) {
const scriptUrl = 'https://plausible.io/js/plausible.outbound-links.tagged-events.js'
const scriptUrl =
'https://plausible.io/js/plausible.outbound-links.tagged-events.js'
response = await fetch(scriptUrl)
if (response.ok) event.waitUntil(cache.put(event.request, response.clone()))
}
return response
}