addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)); }); function getDisplayName(namespace) { //check if the namespace is in the displayNames object. if not, return the namespace return displayNames[namespace] || namespace; } async function getPages() { const url = `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects`; const response = await fetch(url, { headers: { 'Authorization': `Bearer ${CLOUDFLARE_API_TOKEN}`, 'Content-Type': 'application/json', }, }); const data = await response.json(); return data.result; } async function getBuilds(namespace) { const url = `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects/${namespace}/deployments`; const response = await fetch(url, { headers: { 'Authorization': `Bearer ${CLOUDFLARE_API_TOKEN}`, 'Content-Type': 'application/json', }, }); const data = await response.json(); return data.result; } function getPagesNamesfromData(data) { let pages = []; for (let i = 0; i < data.length; i++) { pages.push({ name: data[i].name }); } return pages; } function getBuildsNamesfromData(data) { let builds = []; console.log(JSON.stringify(data)); for (let i = 0; i < data.length; i++) { builds.push({ url: data[i].url, created_on: data[i].created_on, environment: data[i].environment, short_id: data[i].short_id, branch: data[i].deployment_trigger.metadata.branch, commit_message: data[i].deployment_trigger.metadata.commit_message, }); } return builds; } function style() { return ` `; } async function rootPageConstructor() { const pages = await getPagesNamesfromData(await getPages()); let html = ` Pages Builds Index

Pages Builds Index

Find all the builds of my Cloudflare Pages here.

`; html += style(); return html; } async function buildsPageConstructor(namespace) { const builds = await getBuildsNamesfromData(await getBuilds(namespace)); const displayName = getDisplayName(namespace); let html = ` Pages Builds Index

Pages Builds Index

${displayName}:

`; for (let i = 0; i < builds.length; i++) { html += ``; } html += `
ID Environment Date URL Branch Commit Message
${builds[i].short_id}${builds[i].environment}${builds[i].created_on}${builds[i].url}${builds[i].branch}${builds[i].commit_message}
`; html += style(); return html; } async function handleRequest(request) { const { pathname } = new URL(request.url); if (pathname === '/') { return new Response(await rootPageConstructor(), { headers: { 'content-type': 'text/html;charset=UTF-8', }, }); } const path = pathname.split('/'); // if the first path is in the getPagesfromData() array, then //return new Response(JSON.stringify(await getPages())); if (path.length === 2) { const pages = await getPagesNamesfromData(await getPages()); for (let i = 0; i < pages.length; i++) { if (pages[i].name === path[1]) { return new Response(await buildsPageConstructor(path[1]), { headers: { 'content-type': 'text/html;charset=UTF-8', }, }); } } } }