Skip to content

Instantly share code, notes, and snippets.

@rhelp
Created April 28, 2024 01:19
Show Gist options
  • Save rhelp/47fe22b6f696749d262994a5a3d226ab to your computer and use it in GitHub Desktop.
Save rhelp/47fe22b6f696749d262994a5a3d226ab to your computer and use it in GitHub Desktop.
import { google } from 'googleapis'
const youtube = google.youtube({
version: 'v3',
auth: process.env.YOUTUBE_API_KEY
})
const channels = [
'UC4w1YQAJMWOz4qtxinq55LQ',
'UCpXBGqwsBkpvcYjsJBQ7LEQ',
'UCSHZKyawb77ixDdsGog4iWA',
'UCBa659QWEk1AI4Tg--mrJ2A'
]
async function getUploadPlaylistId(channelId) {
const response = await youtube.channels.list({
part: 'contentDetails',
id: channelId,
key: process.env.YOUTUBE_API_KEY
})
return response.data.items[0].contentDetails.relatedPlaylists.uploads
}
async function getPlaylistVideos(playlistId) {
const response = await youtube.playlistItems.list({
part: 'id,snippet,contentDetails',
playlistId
})
return response.data.items
}
export const name = 'video'
export const key = 'app:videoCache'
export const interval = (5 * 60 * 1000)
export async function execute(callback) {
console.log('[VIDEOS] Refreshing cache for video feed...')
// Pull latest videos from each channel
let videos = await Promise.all(channels.map(async (channel) => {
return getPlaylistVideos(await getUploadPlaylistId(channel))
}))
// Flatten, sort and slice the 5 most recent videos
videos = videos.flat()
videos = videos.sort((first, second) => {
return new Date(second.snippet.publishedAt) - new Date(first.snippet.publishedAt)
})
videos = videos.slice(0, 5)
callback(videos, null)
console.log('[VIDEOS] Finished!')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment