46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import { assert } from "jsr:@std/assert/assert";
|
|
import { Vids } from "./types/youtube.ts";
|
|
|
|
export async function searchYTVideo(
|
|
videos: Vids,
|
|
): Promise<string | undefined> {
|
|
const query = `${videos.title} ${videos.artist}`;
|
|
const params = new URLSearchParams({
|
|
part: "snippet",
|
|
q: query,
|
|
type: "video",
|
|
key: Deno.env.get("YT_API_KEY")!, // Replace with your actual API key
|
|
});
|
|
|
|
const endpoint =
|
|
`https://www.googleapis.com/youtube/v3/search?${params.toString()}`;
|
|
|
|
const response = await fetch(endpoint);
|
|
if (!response.ok) {
|
|
throw new Error(`YouTube API error: ${response.statusText}`);
|
|
}
|
|
const data = await response.json();
|
|
|
|
const videoId = data.items && data.items.length > 0
|
|
? data.items[0].id.videoId
|
|
: undefined;
|
|
|
|
if (!videoId) {
|
|
throw new Error("No video found for the given title and artist.");
|
|
}
|
|
|
|
return videoId;
|
|
}
|
|
|
|
Deno.test("searchYT", async () => {
|
|
const yt_api_key = Deno.env.get("YT_API_KEY");
|
|
if (!yt_api_key) throw Error("Testing token not found");
|
|
const videoId = await searchYTVideo({
|
|
title: "Here Comes The Sun",
|
|
artist: "The Beatles",
|
|
});
|
|
|
|
console.log("Here's the video ID:", videoId);
|
|
|
|
assert(typeof videoId === "string" && videoId);
|
|
});
|