Created
January 12, 2021 16:13
-
-
Save dustinrouillard/f6ed1c83efa0cb233dcfc18ebb85dc3f to your computer and use it in GitHub Desktop.
CloudFlare worker for first available YouTube thumbnail (maxresdefault or hqdefault)
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
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}); | |
async function fetchImage(id, type = 'maxresdefault') { | |
const req = await fetch(`https://i.ytimg.com/vi/${id}/${type}.jpg`); | |
if (req.status != 200) return await fetchImage(id, 'hqdefault'); | |
return req; | |
}; | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
if (!url.pathname.split('/')[1]) { | |
const def = await fetch('https://img.youtube.com/vi/jNQXAC9IVRw/maxresdefault.jpg'); | |
return new Response(def.body, def); | |
} | |
let videoId = url.pathname.split('/')[1] | |
if (videoId.includes('.jpg')) videoId = videoId.split('.')[0]; | |
const image = await fetchImage(videoId); | |
return new Response(image.body, image); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah got this finally.