1- import { youtubeParser } from '@/lib/utils' ;
1+ import { publicURL , youtubeParser } from '@/lib/utils' ;
22import { createClient } from 'next-sanity' ;
33import type { NextRequest } from 'next/server' ;
44
55const sanityWriteClient = createClient ( {
66 projectId : process . env . NEXT_PUBLIC_SANITY_PROJECT_ID ,
77 dataset : process . env . NEXT_PUBLIC_SANITY_DATASET ,
88 token : process . env . SANITY_API_WRITE_TOKEN ,
9- useCdn : false ,
9+ apiVersion : '2022-03-07' ,
1010 perspective : 'raw'
1111} ) ;
1212
1313export 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- // }
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+ }
2020
2121 const searchParams = request . nextUrl . searchParams ;
22- const youtube = searchParams . get ( 'youtube' ) ;
23- const _id = searchParams . get ( '_id' ) ;
22+ const lastIdParam = searchParams . get ( 'lastId' ) ;
2423
25- if ( ! _id ) {
26- console . error ( 'Missing Sanity ID' ) ;
27- return new Response ( 'Missing Sanity ID' , { status : 404 } ) ;
28- }
24+ try {
25+ // Assume if lastId is missing that the request will be the initial starting the process.
26+ const sanityRead = await sanityWriteClient . fetch (
27+ `*[youtube != null && _id > $lastId]| order(_id)[0]{
28+ _id,
29+ youtube
30+ }` , {
31+ lastId : lastIdParam || ''
32+ } )
2933
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- }
34+ const lastId = sanityRead ?. _id ;
35+
36+ if ( ! lastId ) {
37+ return Response . json ( { success : true , message : `No doc found based on lastId ${ lastId } ` } , { status : 200 } ) ;
38+ }
39+
40+ // These should never match, if they do bail.
41+ if ( ! lastId && lastIdParam ) {
42+ console . error ( 'lastId matches current doc, stopping calls.' ) ;
43+ return new Response ( 'lastId matches current doc, stopping calls.' , { status : 200 } ) ;
44+ }
45+
46+ const id = youtubeParser ( sanityRead ?. youtube ) ;
47+
48+ if ( ! id ) {
49+ console . error ( 'Missing YouTube Id' ) ;
50+ return new Response ( 'Missing YouTube Id' , { status : 404 } ) ;
51+ }
3952
40- try {
4153 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` )
4254 const json = await videoResp . json ( ) ;
4355 if ( videoResp . status !== 200 ) {
@@ -53,12 +65,18 @@ export async function GET(request: NextRequest) {
5365 return new Response ( words , { status : 404 } ) ;
5466 }
5567
56- const sanityUpdate = await sanityWriteClient . patch ( _id ) . set ( {
68+ // Update current doc with stats
69+ const sanityUpdate = await sanityWriteClient . patch ( lastId ) . set ( {
5770 'statistics.youtube.commentCount' : parseInt ( statistics . commentCount ) ,
5871 'statistics.youtube.favoriteCount' : parseInt ( statistics . favoriteCount ) ,
5972 'statistics.youtube.likeCount' : parseInt ( statistics . likeCount ) ,
6073 'statistics.youtube.viewCount' : parseInt ( statistics . viewCount ) ,
6174 } ) . commit ( ) ;
75+
76+ // Trigger next call, don't wait for response
77+ fetch ( publicURL ( ) + `/api/youtube/views?lastId=${ lastId } ` ,
78+ { headers : { authorization : `Bearer ${ process . env . CRON_SECRET } ` } } ) ;
79+
6280 return Response . json ( sanityUpdate ) ;
6381 } catch ( error ) {
6482 console . error ( JSON . stringify ( error ) ) ;
0 commit comments