www/functions/roa/[path].js
Simon Marsh 3970981f1b
All checks were successful
continuous-integration/drone/push Build is passing
test pipeline
2021-12-27 14:15:48 +00:00

66 lines
2.2 KiB
JavaScript

//////////////////////////////////////////////////////////////////////////
export async function onRequest(context) {
// Contents of context object
const {
request, // same as existing Worker API
env, // same as existing Worker API
params, // if filename includes [id] or [[path]]
waitUntil, // same as ctx.waitUntil in existing Worker API
next, // used for middleware or to fetch assets
data, // arbitrary space for passing data between middlewares
} = context;
const url = new URL(request.url)
const key = new Request(url.toString(), request)
const cache = caches.default
// is the page already cached ?
let response = await cache.match(key)
if (!response) {
// no, we must fetch from the explorer
const map={
'dn42_roa_46.json': '/json',
'dn42_roa_bird1_46.conf': '/bird/1/46',
'dn42_roa_bird1_4.conf': '/bird/1/4',
'dn42_roa_bird1_6.conf': '/bird/1/6',
'dn42_roa_bird2_46.conf': '/bird/2/46',
'dn42_roa_bird2_4.conf': '/bird/2/4',
'dn42_roa_bird2_6.conf': '/bird/2/6',
'dn42_roa_obgpd_4.conf': '/obgpd/4',
'dn42_roa_obgpd_6.conf': '/obgpd/6',
'dn42_roa_obgpd_46.conf': '/obgpd/46'
}
const endpoint = map[url.pathname.split("/").pop()]
if (!endpoint) {
return new Response("404 Not Found", {
'status': 404,
'statusText': 'Not Found'
})
}
// fetch from the explorer
const surl = 'https://explorer.burble.com/api/roa' + endpoint
let sreq = new Request(surl, request)
response = await fetch(sreq)
response = new Response(response.body, response)
// set Cache-Control header
response.headers.append("Cache-Control", "public,s-maxage=3600")
// and store in the cache
waitUntil(cache.put(key, response.clone()))
}
// finally, return the response back to the user
return response
}
//////////////////////////////////////////////////////////////////////////
// end of file