Skip to content

Instantly share code, notes, and snippets.

@bcnzer
Created October 10, 2018 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcnzer/8918548fdac4e5cf2ff0675742912b14 to your computer and use it in GitHub Desktop.
Save bcnzer/8918548fdac4e5cf2ff0675742912b14 to your computer and use it in GitHub Desktop.
Example of a worker adding a header value and returning a response in a specific condition
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
var currentDateTime = new Date()
console.log(currentDateTime.getHours())
if (currentDateTime.getHours() > 20) {
console.log('Disabling access as its late')
return new Response('Not found', { status: 404 })
}
console.log('Got request', request)
const response = await fetch(request)
console.log('response received - adding the ben-version to the header')
const newHeaders = new Headers(response.headers)
newHeaders.append('ben-version', '2018-10-10')
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment