This repository has been archived by the owner on Apr 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
90 lines (76 loc) · 1.96 KB
/
mod.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { serve } from "https://deno.land/std@0.114.0/http/server.ts";
const OAuthKey = Deno.env.get("OAUTHKEY");
interface RatingResponse {
kind: "youtube#videoGetRatingResponse";
items: [
{
id: string;
statistics: {
viewCount: number;
likeCount: number;
dislikeCount: number;
favoriteCount: number;
commentCount: number;
};
},
];
}
type DeployResponse = {
videoId: string;
views: number;
likes: number;
dislikes: number;
favorites: number;
comments: number;
} | { error: string };
export async function getVideoStatistics(
id: string,
key = OAuthKey,
): Promise<DeployResponse> {
const response = await fetch(
`https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${key}&part=statistics`,
);
const json: RatingResponse = await response.json();
if (!json?.items?.[0]?.statistics) {
return { error: "Unable to get statistics for this video id" };
}
const { viewCount, commentCount, dislikeCount, favoriteCount, likeCount } =
json.items[0].statistics;
return {
videoId: id,
likes: likeCount,
dislikes: dislikeCount,
views: viewCount,
comments: commentCount,
favorites: favoriteCount,
};
}
async function handler(req: Request): Promise<Response> {
const args = req.url.split(/\?|&/).slice(1);
const parsed: { [key: string]: string } = {};
const headers = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
};
for (const arg of args) {
const value = arg.split("=");
parsed[value[0]] = value.slice(1).join();
}
if (!parsed.id) {
return new Response(
JSON.stringify(
{ error: "You are missing one of these arguments: id" },
null,
1,
),
{
headers,
},
);
}
const statistics = await getVideoStatistics(parsed.id, parsed?.key);
return new Response(JSON.stringify(statistics, null, 1), {
headers,
});
}
await serve(handler);