Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CloudFlare worker - Enrich tweet using mircolink.io
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request)
{
const url = new URL(request.url);
const id = url.pathname;
const tweet = await fetchTweet(id);
let result = new HTMLRewriter()
.on('a:first-of-type', { async element(element) {
if(element.hasAttribute('href')) {
const link = await fetchLink(element.getAttribute('href'));
if(link.status == 'success' && link.data.image) {
element.after('<img href="'+link.data.image.url+'" >', { html: true });
}
}
}}).transform(new Response(tweet.html))
tweet.html = await result.text();
return new Response(JSON.stringify(tweet), {
status: 200,
headers: {
"content-type": "application/json;charset=UTF-8"
}
})
}
async function fetchTweet(id)
{
const tweet = await fetch('https://publish.twitter.com/oembed?omit_script=1&url=https://twitter.com/_/status'+id)
.then((response) => {
return response.json()
});
console.log(tweet.html);
return tweet;
}
async function fetchLink(url)
{
const link = await fetch('https://api.microlink.io/?url='+url)
.then((response) => {
return response.json()
});
return link;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment