Skip to content

Commit 62467a4

Browse files
update youtube statistics
1 parent a4f8717 commit 62467a4

File tree

7 files changed

+7306
-413
lines changed

7 files changed

+7306
-413
lines changed

app/api/cron/route.tsx

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { publicURL } from '@/lib/utils';
2+
import { createClient } from 'next-sanity';
3+
import type { NextRequest } from 'next/server';
4+
5+
const sanityReadClient = createClient({
6+
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
7+
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
8+
token: process.env.SANITY_API_READ_TOKEN,
9+
apiVersion: '2022-03-07',
10+
perspective: 'raw'
11+
});
12+
13+
export async function GET(request: NextRequest) {
14+
const authHeader = request.headers.get('authorization');
15+
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
16+
return new Response('Unauthorized', {
17+
status: 401,
18+
});
19+
}
20+
21+
//Get all YouTube ID's and make calls
22+
const docs = await sanityReadClient.fetch(`*[youtube != null]{_id,youtube}`);
23+
for (const doc of docs) {
24+
const result = await fetch(publicURL() + `/api/youtube/views?youtube=${doc.youtube}&_id=${doc._id}`)
25+
console.debug(result.status);
26+
}
27+
28+
return Response.json({ success: true });
29+
}

app/api/youtube/views/route.tsx

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { youtubeParser } from '@/lib/utils';
2+
import { createClient } from 'next-sanity';
3+
import type { NextRequest } from 'next/server';
4+
5+
const sanityWriteClient = createClient({
6+
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
7+
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
8+
token: process.env.SANITY_API_WRITE_TOKEN,
9+
useCdn: false,
10+
perspective: 'raw'
11+
});
12+
13+
export async function GET(request: NextRequest) {
14+
// const authHeader = request.headers.get('authorization');
15+
// if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
16+
// return new Response('Unauthorized', {
17+
// status: 401,
18+
// });
19+
// }
20+
21+
const searchParams = request.nextUrl.searchParams;
22+
const youtube = searchParams.get('youtube');
23+
const _id = searchParams.get('_id');
24+
25+
if (!_id) {
26+
console.error('Missing Sanity ID');
27+
return new Response('Missing Sanity ID', { status: 404 });
28+
}
29+
30+
if (!youtube) {
31+
console.error('Missing YouTube URL');
32+
return new Response('Missing YouTube URL', { status: 404 });
33+
}
34+
const id = youtubeParser(youtube)
35+
if (!id) {
36+
console.error('Missing YouTube Id');
37+
return new Response('Missing YouTube Id', { status: 404 });
38+
}
39+
40+
try {
41+
const videoResp = await fetch(`https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${process.env.YOUTUBE_API_KEY}&fields=items(id,statistics)&part=statistics`)
42+
const json = await videoResp.json();
43+
if (videoResp.status !== 200) {
44+
console.error(JSON.stringify(json));
45+
return Response.json(json, { status: videoResp.status })
46+
}
47+
console.debug(JSON.stringify(json));
48+
const statistics = json?.items?.at(0)?.statistics;
49+
50+
if (!statistics) {
51+
const words = `No statistics found for YouTube Id ${id}`
52+
console.error(words);
53+
return new Response(words, { status: 404 });
54+
}
55+
56+
const sanityUpdate = await sanityWriteClient.patch(_id).set({
57+
'statistics.youtube.commentCount': parseInt(statistics.commentCount),
58+
'statistics.youtube.favoriteCount': parseInt(statistics.favoriteCount),
59+
'statistics.youtube.likeCount': parseInt(statistics.likeCount),
60+
'statistics.youtube.viewCount': parseInt(statistics.viewCount),
61+
}).commit();
62+
return Response.json(sanityUpdate);
63+
} catch (error) {
64+
console.error(JSON.stringify(error));
65+
return Response.json({ success: false }, { status: 404 });
66+
}
67+
}

lib/utils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@ export const publicURL = () => {
2727
: "http://localhost:3000";
2828
};
2929

30-
export const delay = async (ms: number) => new Promise((res) => setTimeout(res, ms));
30+
export const delay = async (ms: number) => new Promise((res) => setTimeout(res, ms));

0 commit comments

Comments
 (0)