Created
November 21, 2021 20:09
-
-
Save MehediH/ba0f8842583bc51728c95bd7ab04987d to your computer and use it in GitHub Desktop.
cazoo cloudflare worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cazooApiUrl = "https://www.cazoo.co.uk/api/search?sort=createdAt-desc&runningCosts=ulezChargeExempt&fuelType=Petrol%2CElectric%2CPlug_in_Hybrid%2CHybrid&gearbox=Automatic&ownershipType=purchase&maxMonthlyPrice=280"; | |
const discordWebhookUrl = "https://discord.com/api/webhooks/ENTER_YOUR_WEBHOOK" | |
/* | |
For this to work, you need to setup Workers KV https://developers.cloudflare.com/workers/runtime-apis/kv | |
Here, my KV namespace is called CAZOO | |
For the worker to actually get triggered, you'll also need to set up a cron job from the Workers UI in Cloudflare | |
*/ | |
async function handleRequest() { | |
const lastCheck = JSON.parse(await CAZOO.get("LAST_CHECK")) | |
const { results } = await fetch(cazooApiUrl).then(res => res.json()) | |
const newCars = results.filter(c => new Date(c.createdAt) > new Date(lastCheck)) | |
await CAZOO.put("LAST_CHECK", JSON.stringify(new Date())) | |
if(newCars.length === 0) return; | |
const message = { | |
"content": `**${newCars.length} new car${newCars.length === 1 ? '' : 's'} added **`, | |
"embeds": newCars.map(car => { | |
const pcmPricing = Object.entries(car.pricing.pcmPrice).filter(i => i[0] !== 'lowest').map(i => `${i[0].toUpperCase()}: £${i[1].value}`).join("\n") | |
return { | |
"title": `${car.make} ${car.model} (${car.modelYear})`, | |
"description": `Mileage: ${car.mileage} miles\nFull Price: £${car.pricing.fullPrice.value}${pcmPricing ? `\n${pcmPricing}` : null}`, | |
"url": `https://www.cazoo.co.uk/car-details/${car.id}`, | |
"color": 5814783, | |
"footer": { | |
"text": car.displayVariant | |
}, | |
"image": { | |
"url": car.images.main.url | |
} | |
} | |
}) | |
} | |
await fetch(discordWebhookUrl, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify(message), | |
} | |
); | |
} | |
addEventListener('scheduled', event => { | |
event.waitUntil( | |
handleRequest() | |
) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment