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
+ }
0 commit comments