import { Injectable } from '@nestjs/common' import { HttpService } from '../http' import { YoutubePlaylist, YoutubeVideo } from './types' type resources = 'videos' | 'playlists' | 'playlistItems' @Injectable() export class Youtube { constructor(private readonly httpService: HttpService) {} async getPlaylistById(id: string): Promise { const response = await this.fetch('playlists', { field: 'id', value: id }) const playlist = response.items.shift() return { id: playlist.id, snippet: { ...playlist.snippet, publishedAt: new Date(playlist.snippet.publishedAt) }, } } async getVideoById(id: string): Promise { const response = await this.fetch('videos', { field: 'id', value: id }) const video = response.items.shift() return { id: video.id, snippet: { ...video.snippet, publishedAt: new Date(video.snippet.publishedAt) }, } } async findPlaylistsByChannelId(channelId: string): Promise { const response = await this.fetch('playlists', { field: 'channelId', value: channelId }) const videos: any[] = response.items return videos.map(playlist => ({ id: playlist.id, snippet: { ...playlist.snippet, publishedAt: new Date(playlist.snippet.publishedAt) }, })) } async findVideosByPlaylistId(playlistId: string): Promise { const response = await this.fetch('playlistItems', { field: 'playlistId', value: playlistId }) const videos: any[] = response.items return videos.map(video => ({ id: video.snippet.resourceId.videoId, snippet: { ...video.snippet, publishedAt: new Date(video.snippet.publishedAt) }, })) } private async fetch(resource: resources, filter: { field: string; value: string }): Promise { return await this.httpService.get(this.getURL(resource, filter), { name: this.constructor.name, }) } private getURL(resource: resources, filter: { field: string; value: string }, maxResults = 50): string { return `https://www.googleapis.com/youtube/v3/${resource}?maxResults=${maxResults}&key=${globalThis.secret.firebase_config.api_key}&part=snippet&${filter.field}=${filter.value}` } }