55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
import { youtube_v3 as youtube } from 'googleapis';
|
|
|
|
export default class YouTube {
|
|
apiKey: string;
|
|
client: youtube.Youtube;
|
|
|
|
constructor(apiKey: string)
|
|
{
|
|
this.apiKey = apiKey;
|
|
this.client = new youtube.Youtube({ auth: apiKey });
|
|
}
|
|
|
|
/**
|
|
* Returns the video info for the given video ID.
|
|
*
|
|
* @param videoId YouTube Video ID
|
|
* @returns Video info
|
|
*/
|
|
async getVideoInfo(videoId: string): Promise<youtube.Schema$Video | null>
|
|
{
|
|
const response = await this.client.videos.list({
|
|
part: ['snippet', 'contentDetails'],
|
|
id: [videoId],
|
|
});
|
|
|
|
if (response.data.items === undefined || response.data.items.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
return response.data.items[0];
|
|
}
|
|
|
|
/**
|
|
* Searches for videos matching the given query.
|
|
*
|
|
* @param query Search query
|
|
* @param maxResults Maximum number of results to return
|
|
* @returns List of search results
|
|
*/
|
|
async searchVideos(query: string, maxResults: number | undefined = 50): Promise<youtube.Schema$SearchResult[]>
|
|
{
|
|
const searchQuery = {
|
|
part: ['snippet'],
|
|
maxResults: maxResults,
|
|
q: query,
|
|
safeSearch: 'none',
|
|
type: ['video'],
|
|
};
|
|
|
|
const response = await this.client.search.list(searchQuery);
|
|
|
|
return response.data.items ?? [];
|
|
}
|
|
}
|