shivam413 commited on
Commit
a19d589
·
verified ·
1 Parent(s): 1c25f54

Create search.ts

Browse files
Files changed (1) hide show
  1. pages/api/search.ts +49 -0
pages/api/search.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { NextApiRequest, NextApiResponse } from "next"
2
+ import { execFile } from "node:child_process"
3
+
4
+ type YtResult = {
5
+ id: string
6
+ title: string
7
+ url: string
8
+ duration?: number
9
+ thumbnails?: { url: string; width?: number; height?: number }[]
10
+ }
11
+
12
+ export default function handler(req: NextApiRequest, res: NextApiResponse) {
13
+ const q = (req.query.q || "").toString().trim()
14
+ if (!q) return res.status(400).json({ error: "Missing q" })
15
+
16
+ const limit = Math.max(1, Math.min(20, parseInt((req.query.limit || "10").toString(), 10) || 10))
17
+ const term = `ytsearch${limit}:${q}`
18
+
19
+ execFile(
20
+ "yt-dlp",
21
+ ["-J", term, "--no-warnings"],
22
+ { maxBuffer: 10 * 1024 * 1024 },
23
+ (err, stdout, stderr) => {
24
+ if (err) {
25
+ console.error("yt-dlp search failed", err, stderr)
26
+ return res.status(500).json({ error: "search_failed" })
27
+ }
28
+ try {
29
+ const data = JSON.parse(stdout)
30
+ const entries = Array.isArray(data?.entries) ? data.entries : []
31
+ const results: YtResult[] = entries
32
+ .filter((e: any) => e?.id && e?.title)
33
+ .map((e: any) => ({
34
+ id: e.id,
35
+ title: e.title,
36
+ url: `https://www.youtube.com/watch?v=${e.id}`,
37
+ duration: typeof e.duration === "number" ? e.duration : undefined,
38
+ thumbnails: Array.isArray(e.thumbnails)
39
+ ? e.thumbnails.map((t: any) => ({ url: t.url, width: t.width, height: t.height }))
40
+ : undefined,
41
+ }))
42
+ res.json({ results })
43
+ } catch (parseErr) {
44
+ console.error("Failed to parse yt-dlp JSON", parseErr)
45
+ res.status(500).json({ error: "parse_failed" })
46
+ }
47
+ }
48
+ )
49
+ }