Skip to content

Commit bca49b1

Browse files
update cron to run based on sanity lastId
1 parent 62467a4 commit bca49b1

File tree

2 files changed

+48
-42
lines changed

2 files changed

+48
-42
lines changed

app/api/cron/route.tsx

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,17 @@
11
import { publicURL } from '@/lib/utils';
2-
import { createClient } from 'next-sanity';
32
import type { NextRequest } from 'next/server';
43

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) {
4+
export function GET(request: NextRequest) {
145
const authHeader = request.headers.get('authorization');
156
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
167
return new Response('Unauthorized', {
178
status: 401,
189
});
1910
}
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-
}
11+
// Don't await just trigger
12+
console.debug('youtube views triggered');
13+
fetch(publicURL() + `/api/youtube/views`,
14+
{ headers: { authorization: `Bearer ${process.env.CRON_SECRET}` } });
2715

2816
return Response.json({ success: true });
2917
}

app/api/youtube/views/route.tsx

Lines changed: 43 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,55 @@
1-
import { youtubeParser } from '@/lib/utils';
1+
import { publicURL, youtubeParser } from '@/lib/utils';
22
import { createClient } from 'next-sanity';
33
import type { NextRequest } from 'next/server';
44

55
const 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

1313
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-
// }
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

Comments
 (0)