Skip to content

Instantly share code, notes, and snippets.

@dtanner
Last active December 18, 2020 15:03
Show Gist options
  • Save dtanner/54b10ef8932b026afec0398495b5b2b5 to your computer and use it in GitHub Desktop.
Save dtanner/54b10ef8932b026afec0398495b5b2b5 to your computer and use it in GitHub Desktop.
MORC Trail Conditions Cloudflare Reformatter
/*
The https://trails.morcmtb.org/ site has way too much crap that I don't care about.
I just want to quickly see what trails are open.
This is a cloudflare worker that hits the trails API and builds a concise HTML view of the conditions.
It could just be statically hosted javascript, but this was also an excuse to try out workers.
*/
addEventListener("fetch", event => {
return event.respondWith(handleRequest())
})
async function handleRequest() {
const init = {
headers: {
"content-type": "text/html;charset=UTF-8"
}
}
const response = await fetch('https://api.morcmtb.org/v1/trails')
const results = await formatResponse(response)
return new Response(results, init)
}
function isStatusOld(updatedAt) {
const MILLIS_IN_DAY = 1000 * 60 * 60 * 24
let ageDays = Math.round((Date.now() - updatedAt) / MILLIS_IN_DAY)
return ageDays > 7
}
async function formatResponse(response) {
const conditions = await response.json()
const outputString = conditions.reduce(function (acc, value) {
let statusColor = "red"
if (isStatusOld(value.updatedAt)) {
statusColor = "gray"
} else if (value.trailStatus == "Open") {
statusColor = "green"
}
isStatusOld(value.updatedAt)
let updatedAt = new Date(value.updatedAt).toLocaleString("en-US")
let description = value.description ? value.description : ""
const formattedLine = `
<b>
<span style="color: ${statusColor};font-size:36px;"
onclick="document.getElementById('description-${value.trailName.replace(/\s/g, "")}').style.display = 'block';">${value.trailName}
</span>
</b>
<i><span style="font-size:24px">${updatedAt}</span></i>
<span id="description-${value.trailName.replace(/\s/g, '')}" style="display: none;font-size:24px">${description}</span>
`
return `${acc}${formattedLine}<br>`
}, "")
const legend = `
<br><b>Click on a trail name to view its current conditions description</b>
<br><span style="color: green">green = open</span>
<br/><span style="color: red">red = closed</span>
<br/><span style="color: gray">gray = unsure; updated date is old</span>
`
return `${outputString}${legend}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment