Skip to content

Instantly share code, notes, and snippets.

@switz
Last active June 10, 2022 17:05
Show Gist options
  • Save switz/51ce90492e2953fbd20de053706efd21 to your computer and use it in GitHub Desktop.
Save switz/51ce90492e2953fbd20de053706efd21 to your computer and use it in GitHub Desktop.
Get your accounts latest tweets in a CF worker
const cacheVersion = 1;
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
const token = ''; // twitter refresh token
const twitterId = 3380909105; // my twitter id
const params = [
'tweet.fields=created_at,public_metrics,attachments',
'expansions=author_id,entities.mentions.username,attachments.media_keys',
'media.fields=preview_image_url,height,width,url',
'user.fields=created_at',
'max_results=10',
'exclude=retweets,replies'
].join('&');
const endpointURL = `https://api.twitter.com/2/users/${twitterId}/tweets?${params}`;
async function getRequest() {
// fetch tweets
const res = await fetch(endpointURL, {
headers: {
"authorization": `Bearer ${token}`
}
});
const json = await res.json();
if (json) {
return [json.data, json.includes, res.status];
} else {
throw new Error('Unsuccessful request')
}
}
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(event) {
const request = event.request;
const cache = caches.default;
const cacheKey = [request.url, cacheVersion].join(':');
// Get this request from this zone's cache
let response = await cache.match(cacheKey)
// if cache is hit, add optional header
if (response) {
//response.headers.append("X-HIT-CACHE", "true");
} else {
const [data, includes, status] = await getRequest();
const mappedData = data.map(tweet => {
return {
...tweet,
media: !tweet.attachments ? [] : tweet.attachments.media_keys?.map(mk => includes.media.find(m => m.media_key === mk)),
}
});
response = new Response(JSON.stringify(mappedData), {
status
});
// Cache API respects Cache-Control headers. Setting max-age to 300
// will limit the response to be in cache for 300 seconds max
response.headers.append("Cache-Control", "max-age=300");
response.headers.append("Content-Type", "application/json");
response.headers.append("Access-Control-Allow-Origin", "*");
// Use waitUntil so computational expensive tasks don"t delay the response
event.waitUntil(cache.put(cacheKey, response.clone()));
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment