-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
176 lines (155 loc) · 5.45 KB
/
route.ts
File metadata and controls
176 lines (155 loc) · 5.45 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { NextResponse } from 'next/server';
import { revalidatePath, revalidateTag } from 'next/cache';
import { AVAILABLE_LOCALES } from '../../../i18n/routing';
import { nonEmpty } from '../../utils/config';
type RevalidateTypes =
| 'full'
| 'all-feeds'
| 'all-gbfs-feeds'
| 'all-gtfs-rt-feeds'
| 'all-gtfs-feeds'
| 'specific-feeds';
interface RevalidateBody {
feedIds: string[]; // only for 'specific-feeds' revalidation type
type: RevalidateTypes;
}
const defaultRevalidateOptions: RevalidateBody = {
// By default it will revalidate nothing
type: 'specific-feeds',
feedIds: [],
};
/**
* GET handler for the Vercel cron job that revalidates all feed pages once a day.
* Vercel automatically passes Authorization: Bearer <CRON_SECRET> with each invocation.
* Configured in vercel.json under "crons" (schedule: 0 9 * * * = 4am EST / 9am UTC).
*/
export async function GET(req: Request): Promise<NextResponse> {
const authHeader = req.headers.get('authorization');
const cronSecret = process.env.CRON_SECRET;
if (cronSecret == null) {
return NextResponse.json(
{ ok: false, error: 'Server misconfigured: CRON_SECRET missing' },
{ status: 500 },
);
}
if (authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json(
{ ok: false, error: 'Unauthorized' },
{ status: 401 },
);
}
try {
revalidateTag('guest-feeds', 'max');
revalidatePath('/[locale]/feeds/[feedDataType]/[feedId]', 'layout');
console.log(
'[cron] revalidate /api/revalidate: all-feeds revalidation triggered',
);
return NextResponse.json({
ok: true,
message: 'All feeds revalidated successfully',
});
} catch (error) {
console.error(
'[cron] revalidate /api/revalidate: revalidation failed:',
error,
);
return NextResponse.json(
{ ok: false, error: 'Revalidation failed' },
{ status: 500 },
);
}
}
export async function POST(req: Request): Promise<NextResponse> {
const expectedSecret = nonEmpty(process.env.REVALIDATE_SECRET);
if (expectedSecret == null) {
return NextResponse.json(
{ ok: false, error: 'Server misconfigured: REVALIDATE_SECRET missing' },
{ status: 500 },
);
}
const providedSecret = req.headers.get('x-revalidate-secret');
if (providedSecret == null || providedSecret !== expectedSecret) {
return NextResponse.json(
{ ok: false, error: 'Unauthorized' },
{ status: 401 },
);
}
let payload: RevalidateBody = { ...defaultRevalidateOptions }; // default to full revalidation if body is missing/invalid
try {
const body = (await req.json()) as RevalidateBody;
payload = {
...defaultRevalidateOptions,
...body,
};
} catch (parseError) {
console.error(
'Failed to parse request body, falling back to defaults:',
parseError,
);
payload = { ...defaultRevalidateOptions };
}
// NOTE
// revalidatePath = triggers revalidation for entire page cache
// revalidateTag = triggers revalidation for API calls using `unstable_cache` with matching tags (e.g., feed-123, guest-feeds)
try {
// clears cache for entire site
if (payload.type === 'full') {
revalidateTag('guest-feeds', 'max');
revalidatePath('/', 'layout');
}
// clears cache for all feed pages (ISR-cached layout)
if (payload.type === 'all-feeds') {
revalidateTag('guest-feeds', 'max');
revalidatePath('/[locale]/feeds/[feedDataType]/[feedId]', 'layout');
}
// clears cache for all GBFS feed pages (ISR-cached layout)
if (payload.type === 'all-gbfs-feeds') {
revalidateTag('feed-type-gbfs', 'max');
revalidatePath('/[locale]/feeds/gbfs/[feedId]', 'layout');
}
// clears cache for all GTFS feed pages (ISR-cached layout)
if (payload.type === 'all-gtfs-feeds') {
revalidateTag('feed-type-gtfs', 'max');
revalidatePath('/[locale]/feeds/gtfs/[feedId]', 'layout');
}
// clears cache for all GTFS RT feed pages (ISR-cached layout)
if (payload.type === 'all-gtfs-rt-feeds') {
revalidateTag('feed-type-gtfs_rt', 'max');
revalidatePath('/[locale]/feeds/gtfs_rt/[feedId]', 'layout');
}
// clears cache for specific feed pages (ISR-cached page) + localized paths
if (payload.type === 'specific-feeds') {
const localPaths = AVAILABLE_LOCALES.filter((loc) => loc !== 'en');
const pathsToRevalidate: string[] = [];
payload.feedIds.forEach((id) => {
revalidateTag(`feed-${id}`, 'max');
// The id will try to revalidate all feed types with that id, but that's necessary since we don't know the feed type here and it's not a big deal if we revalidate some non-existent pages
pathsToRevalidate.push(`/feeds/gtfs/${id}`);
pathsToRevalidate.push(`/feeds/gtfs_rt/${id}`);
pathsToRevalidate.push(`/feeds/gbfs/${id}`);
});
console.log('Revalidating paths:', pathsToRevalidate);
pathsToRevalidate.forEach((path) => {
revalidatePath(path);
revalidatePath(path + '/map');
localPaths.forEach((loc) => {
revalidatePath(`/${loc}${path}`);
revalidatePath(`/${loc}${path}/map`);
});
});
}
return NextResponse.json({
ok: true,
message: 'Revalidation triggered successfully',
});
} catch (error) {
console.error('Revalidation failed:', error);
return NextResponse.json(
{
ok: false,
error: 'Failed to revalidate',
},
{ status: 500 },
);
}
}