-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper.ts
48 lines (42 loc) · 1.41 KB
/
scraper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { z } from "zod";
const $response = z.object({
data: z.object({
items: z.array(
z.object({
content: z.object({
id: z.string(),
registeredAt: z.string().datetime({ offset: true }),
}),
}),
),
}),
meta: z.object({
status: z.literal(200),
}),
});
export function buildUrl({ tags, duration: range, today }: { tags: string[]; today: Date; duration: number }) {
const url = new URL("/v1/playlist/search", "https://nvapi.nicovideo.jp");
url.searchParams.set("tag", tags.join(" "));
url.searchParams.set("sortKey", "registeredAt");
url.searchParams.set("sortOrder", "desc");
url.searchParams.set("pageSize", (64).toString());
url.searchParams.set("page", (1).toString());
url.searchParams.set("_frontendId", "6");
url.searchParams.set("_frontendVersion", "0");
return url.toString();
}
export async function scrape({ tags, duration: duration, today }: { tags: string[]; today: Date; duration: number }) {
const url = buildUrl({ tags, duration: duration, today });
const data = await fetch(url).then((res) => res.json());
const parsedData = $response.safeParse(data);
if (!parsedData.success) {
console.error(parsedData.error);
throw new Error("Failed to parse response");
}
return {
videos: parsedData.data.data.items.map((v) => ({
sourceId: v.content.id,
postedAt: new Date(v.content.registeredAt),
})),
};
}