diff --git a/app/(site)/(show)/movie/[id]/page.tsx b/app/(site)/(show)/movie/[id]/page.tsx index 976a2fd..942663f 100644 --- a/app/(site)/(show)/movie/[id]/page.tsx +++ b/app/(site)/(show)/movie/[id]/page.tsx @@ -2,6 +2,8 @@ import { createShowMetadata, createShowPage } from '../../showPage'; export const revalidate = 86400; +export const generateStaticParams = async () => []; + export const generateMetadata = createShowMetadata('movie'); const MoviePage = createShowPage('movie'); diff --git a/app/(site)/(show)/showPage.tsx b/app/(site)/(show)/showPage.tsx index 5042e43..f944657 100644 --- a/app/(site)/(show)/showPage.tsx +++ b/app/(site)/(show)/showPage.tsx @@ -6,7 +6,7 @@ import JsonLd from '@/components/JsonLd'; import detailsQuery from '@/data/queries/details'; import { SITE_URL, TITLE } from '@/env'; import getQueryClient from '@/lib/queryClient'; -import { showPath } from '@/lib/utils'; +import { isMissing, showPath } from '@/lib/utils'; import Container from './container'; @@ -41,8 +41,10 @@ export const createShowMetadata = url: path } }; - } catch (_) { - return notFound(); + } catch (error) { + if (isMissing(error)) return notFound(); + + throw error; } }; @@ -54,7 +56,11 @@ export const createShowPage = (showType: Show['type']) => { if (!showId) return notFound(); - const details = await queryClient.fetchQuery(detailsQuery({ showId, showType })).catch(() => null); + const details = await queryClient.fetchQuery(detailsQuery({ showId, showType })).catch((error) => { + if (isMissing(error)) return null; + + throw error; + }); if (!details) return notFound(); diff --git a/app/(site)/(show)/tv/[id]/page.tsx b/app/(site)/(show)/tv/[id]/page.tsx index eb6fc79..7fe3852 100644 --- a/app/(site)/(show)/tv/[id]/page.tsx +++ b/app/(site)/(show)/tv/[id]/page.tsx @@ -2,6 +2,8 @@ import { createShowMetadata, createShowPage } from '../../showPage'; export const revalidate = 86400; +export const generateStaticParams = async () => []; + export const generateMetadata = createShowMetadata('tv'); const SeriesPage = createShowPage('tv'); diff --git a/app/(site)/person/[id]/page.tsx b/app/(site)/person/[id]/page.tsx index 308bad9..3b07e1e 100644 --- a/app/(site)/person/[id]/page.tsx +++ b/app/(site)/person/[id]/page.tsx @@ -8,6 +8,7 @@ import Person from '@/components/Person'; import personQuery from '@/data/queries/person'; import { SITE_URL, TITLE } from '@/env'; import getQueryClient from '@/lib/queryClient'; +import { isMissing } from '@/lib/utils'; interface Props { params: { id: string }; @@ -15,6 +16,8 @@ interface Props { export const revalidate = 86400; +export const generateStaticParams = async () => []; + export const generateMetadata = async ({ params: { id } }: Props): Promise => { const queryClient = getQueryClient(); @@ -36,15 +39,21 @@ export const generateMetadata = async ({ params: { id } }: Props): Promise = async ({ params: { id } }) => { const queryClient = getQueryClient(); - const profile = await queryClient.fetchQuery(personQuery({ personId: id })).catch(() => null); + const profile = await queryClient.fetchQuery(personQuery({ personId: id })).catch((error) => { + if (isMissing(error)) return null; + + throw error; + }); if (!profile) return notFound(); diff --git a/app/api/tmdb/[...path]/route.ts b/app/api/tmdb/[...path]/route.ts index cc829b0..7a91534 100644 --- a/app/api/tmdb/[...path]/route.ts +++ b/app/api/tmdb/[...path]/route.ts @@ -1,6 +1,9 @@ import { NextRequest, NextResponse } from 'next/server'; import { MOVIE_DB_API_URL, MOVIE_DB_TOKEN } from '@/env'; +import { PRIVATE_CACHE_CONTROL, PUBLIC_CACHE_CONTROL, REVALIDATE } from '@/lib/cache'; + +import trim from './trim'; type TMDBParams = { params: { @@ -8,15 +11,25 @@ type TMDBParams = { }; }; +const upstream = (path: string[], searchParams: URLSearchParams) => { + const params = new URLSearchParams(searchParams); + + params.delete('preventCache'); + + const query = params.toString(); + + return `${MOVIE_DB_API_URL}/${path.join('/')}${query ? `?${query}` : ''}`; +}; + +const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${MOVIE_DB_TOKEN}` }; + export async function GET({ nextUrl: { searchParams } }: NextRequest, { params: { path } }: TMDBParams) { + const isPrivate = Boolean(searchParams.get('preventCache') || searchParams.get('session_id')); + try { - const params = searchParams.toString(); - const response = await fetch(`${MOVIE_DB_API_URL}/${path.join('/')}${params ? `?${params}` : ''}`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${MOVIE_DB_TOKEN}` - }, - next: searchParams.get('preventCache') || searchParams.get('session_id') ? undefined : { revalidate: 3600 } + const response = await fetch(upstream(path, searchParams), { + headers, + next: isPrivate ? undefined : { revalidate: REVALIDATE } }); if (!response.ok) { @@ -25,7 +38,9 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest, { params: const data = await response.json(); - return NextResponse.json(data); + return NextResponse.json(trim(path.join('/'), data), { + headers: { 'Cache-Control': isPrivate ? PRIVATE_CACHE_CONTROL : PUBLIC_CACHE_CONTROL } + }); } catch (error) { return NextResponse.json({ error: 'An error occurred' }, { status: 500 }); } @@ -34,14 +49,10 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest, { params: export async function POST(request: NextRequest, { params: { path } }: TMDBParams) { try { const requestBody = await request.json(); - const searchParams = request.nextUrl.searchParams.toString(); - const response = await fetch(`${MOVIE_DB_API_URL}/${path.join('/')}?${searchParams}`, { + const response = await fetch(upstream(path, request.nextUrl.searchParams), { method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${MOVIE_DB_TOKEN}` - }, + headers, body: JSON.stringify(requestBody) }); @@ -51,7 +62,7 @@ export async function POST(request: NextRequest, { params: { path } }: TMDBParam const data = await response.json(); - return NextResponse.json(data); + return NextResponse.json(data, { headers: { 'Cache-Control': PRIVATE_CACHE_CONTROL } }); } catch (error) { return NextResponse.json({ error: 'An error occurred' }, { status: 500 }); } diff --git a/app/api/tmdb/[...path]/trim.ts b/app/api/tmdb/[...path]/trim.ts new file mode 100644 index 0000000..b682a9d --- /dev/null +++ b/app/api/tmdb/[...path]/trim.ts @@ -0,0 +1,76 @@ +type Unknown = Record; + +const identity = (payload: Unknown) => payload; + +const named = ({ id, name, profile_path }: Unknown) => ({ id, name, profile_path }); + +const castMember = (member: Unknown) => ({ + ...named(member), + ...('character' in member ? { character: member.character } : {}), + ...(member.roles ? { roles: member.roles.map(({ character }: Unknown) => ({ character })) } : {}), + ...(member.total_episode_count != null ? { total_episode_count: member.total_episode_count } : {}) +}); + +const crewMember = (member: Unknown) => ({ + ...named(member), + ...(member.job ? { job: member.job } : {}), + ...(member.jobs ? { jobs: member.jobs.map(({ job }: Unknown) => ({ job })) } : {}), + ...(member.total_episode_count != null ? { total_episode_count: member.total_episode_count } : {}) +}); + +const withPhoto = ({ profile_path }: Unknown) => Boolean(profile_path); + +const credits = ({ cast = [], crew = [], ...rest }: Unknown) => ({ + ...rest, + cast: cast.filter(withPhoto).map(castMember), + crew: crew.filter(withPhoto).map(crewMember) +}); + +const personCredit = (credit: Unknown) => ({ + media_type: credit.media_type, + id: credit.id, + overview: credit.overview, + poster_path: credit.poster_path, + backdrop_path: credit.backdrop_path, + vote_average: credit.vote_average, + vote_count: credit.vote_count, + ...(credit.media_type === 'tv' + ? { first_air_date: credit.first_air_date, name: credit.name } + : { release_date: credit.release_date, title: credit.title }) +}); + +const shown = ({ poster_path, media_type }: Unknown) => Boolean(poster_path) && ['movie', 'tv'].includes(media_type); + +const person = ({ combined_credits, ...profile }: Unknown) => ({ + id: profile.id, + name: profile.name, + biography: profile.biography, + birthday: profile.birthday, + deathday: profile.deathday, + place_of_birth: profile.place_of_birth, + known_for_department: profile.known_for_department, + profile_path: profile.profile_path, + ...(combined_credits + ? { + combined_credits: { + cast: (combined_credits.cast || []).filter(shown).map(personCredit), + crew: (combined_credits.crew || []).filter(shown).map(personCredit) + } + } + : {}) +}); + +const trimmers: Array<[RegExp, (payload: Unknown) => Unknown]> = [ + [/^(movie|tv)\/\d+\/(aggregate_)?credits$/, credits], + [/^person\/\d+$/, person] +]; + +const trim = (path: string, payload: unknown) => { + if (!payload || typeof payload !== 'object') return payload; + + const [, trimmer = identity] = trimmers.find(([pattern]) => pattern.test(path)) || []; + + return trimmer(payload as Unknown); +}; + +export default trim; diff --git a/data/clients/Http.ts b/data/clients/Http.ts index 7cd9353..a4ef5e1 100644 --- a/data/clients/Http.ts +++ b/data/clients/Http.ts @@ -1,6 +1,4 @@ -import { isServer } from '@tanstack/react-query'; - -import { SITE_URL } from '@/env'; +import { REVALIDATE } from '@/lib/cache'; type Search = Record; @@ -16,7 +14,7 @@ class Http { base = this.base, search, body, - preventCache = true + preventCache = false }: { method: 'GET' | 'POST'; url: string; @@ -34,7 +32,9 @@ class Http { }, new URLSearchParams()) ); - if (preventCache) { + const uncached = preventCache || method === 'POST'; + + if (uncached) { searchParams.append('preventCache', '1'); } @@ -48,7 +48,7 @@ class Http { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined, - next: preventCache ? undefined : { revalidate: 3600 } + next: uncached ? undefined : { revalidate: REVALIDATE } }); if (!response.ok) { diff --git a/data/clients/movieAdvisor.ts b/data/clients/movieAdvisor.ts index 3c22cf1..af7184a 100644 --- a/data/clients/movieAdvisor.ts +++ b/data/clients/movieAdvisor.ts @@ -1,13 +1,9 @@ import { isServer } from '@tanstack/react-query'; -import { SITE_URL } from '@/env'; +import { MOVIE_DB_API_URL, MOVIE_DB_TOKEN } from '@/env'; import Http from './Http'; -const PUBLIC_ORIGIN = `${SITE_URL?.startsWith('http') ? SITE_URL : `https://${SITE_URL}`}`; - -const ROOT = process.env.NODE_ENV === 'development' ? `http://127.0.0.1:${process.env.PORT || 3000}` : PUBLIC_ORIGIN; - -const movieAdvisor = new Http(`${isServer ? ROOT : ''}/api/tmdb`); +const movieAdvisor = isServer ? new Http(MOVIE_DB_API_URL, `Bearer ${MOVIE_DB_TOKEN}`) : new Http('/api/tmdb'); export default movieAdvisor; diff --git a/lib/cache.ts b/lib/cache.ts new file mode 100644 index 0000000..6ef09ef --- /dev/null +++ b/lib/cache.ts @@ -0,0 +1,7 @@ +export const REVALIDATE = 3600; + +const STALE_WHILE_REVALIDATE = 86400; + +export const PUBLIC_CACHE_CONTROL = `public, s-maxage=${REVALIDATE}, stale-while-revalidate=${STALE_WHILE_REVALIDATE}`; + +export const PRIVATE_CACHE_CONTROL = 'private, no-store'; diff --git a/lib/utils.ts b/lib/utils.ts index 97f1c1a..d607cda 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -91,3 +91,5 @@ export const detectSafari = () => { }; export const isStandaloneApp = () => window.matchMedia('screen and (display-mode: standalone)').matches; + +export const isMissing = (error: unknown) => (error as { status?: number })?.status === 404;