perf(tmdb): trim responses to fields the UI uses, in proxy and server client

Move the trimmer from the route into a shared lib/tmdbTrim and apply it in
the server-side client too (server hits TMDB directly, bypassing the proxy),
so both paths return identical shapes. Show page HTML drops ~22%
(88.4KB -> 68.8KB); TV details payload -90%.
This commit is contained in:
ner committed 2026-09-25 16:05:45 +03:00
1 parent 88f51f783e
commit 8c8d752962
3 files changed
+95 -6

No files matched your search

+2 -3
View File
@@ -2,8 +2,7 @@ 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';
import trimTmdb from '@/lib/tmdbTrim';
type TMDBParams = {
params: {
@@ -38,7 +37,7 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest, { params:
const data = await response.json();
return NextResponse.json(trim(path.join('/'), data), {
return NextResponse.json(trimTmdb(path.join('/'), data), {
headers: { 'Cache-Control': isPrivate ? PRIVATE_CACHE_CONTROL : PUBLIC_CACHE_CONTROL }
});
} catch (error) {
+16 -1
View File
@@ -1,9 +1,24 @@
import { isServer } from '@tanstack/react-query';
import { MOVIE_DB_API_URL, MOVIE_DB_TOKEN } from '@/env';
import trimTmdb from '@/lib/tmdbTrim';
import Http from './Http';
const movieAdvisor = isServer ? new Http(MOVIE_DB_API_URL, `Bearer ${MOVIE_DB_TOKEN}`) : new Http('/api/tmdb');
type Search = Record<string, string | number | boolean | null | undefined>;
const http = isServer ? new Http(MOVIE_DB_API_URL, `Bearer ${MOVIE_DB_TOKEN}`) : new Http('/api/tmdb');
// The browser goes through the /api/tmdb proxy, which trims responses; on the server we hit the
// API directly, so apply the same trim to keep both paths returning identical data.
const movieAdvisor = {
get: <T>(url: string, { params, preventCache }: { params?: Search; preventCache?: boolean } = {}) =>
http.get<T>(url, { params, preventCache }).then((data) => trimTmdb(url, data) as T),
post: <T, B = unknown>(
url: string,
{ params, preventCache }: { params?: Search; preventCache?: boolean } = {},
body?: B
) => http.post<T, B>(url, { params, preventCache }, body)
};
export default movieAdvisor;
@@ -2,6 +2,16 @@ type Unknown = Record<string, any>;
const identity = (payload: Unknown) => payload;
const pick = (source: Unknown, keys: string[]): Unknown => {
const out: Unknown = {};
keys.forEach((key) => {
if (key in source) out[key] = source[key];
});
return out;
};
const named = ({ id, name, profile_path }: Unknown) => ({ id, name, profile_path });
const castMember = (member: Unknown) => ({
@@ -60,15 +70,80 @@ const person = ({ combined_credits, ...profile }: Unknown) => ({
: {})
});
// Keys must survive even when null: mappers distinguish movie from tv via key presence
// (e.g. `'release_date' in item`) and filter on truthy values.
const listItem = (item: Unknown) =>
pick(item, [
'id',
'title',
'name',
'overview',
'poster_path',
'backdrop_path',
'release_date',
'first_air_date',
'vote_average',
'vote_count'
]);
const list = ({ page, total_pages, results }: Unknown) => ({
page,
total_pages,
results: (results || []).map(listItem)
});
const releaseDates = ({ results = [] }: Unknown) => ({
results: results.map(({ release_dates = [] }: Unknown) => ({
release_dates: release_dates
.filter(({ type, release_date }: Unknown) => type && release_date)
.map(({ type, release_date }: Unknown) => ({ type, release_date }))
}))
});
const details = (payload: Unknown) => {
const out = pick(payload, [
'id',
'title',
'name',
'overview',
'poster_path',
'backdrop_path',
'release_date',
'first_air_date',
'vote_average',
'vote_count',
'runtime',
'genres',
'imdb_id',
'tagline',
'status',
'number_of_seasons',
'last_episode_to_air',
'next_episode_to_air'
]);
if ('release_dates' in payload) out.release_dates = releaseDates(payload.release_dates);
return out;
};
const trimmers: Array<[RegExp, (payload: Unknown) => Unknown]> = [
[/^(movie|tv)\/\d+\/(aggregate_)?credits$/, credits],
[/^person\/\d+$/, person]
[/^person\/\d+$/, person],
[/^(movie|tv)\/\d+\/(similar|recommendations)$/, list],
[/^account\/[^/]+\/(favorite|watchlist)\/(movies|tv)$/, list],
[/^(discover|search)\/(movie|tv)$/, list],
[/^trending\/(movie|tv|all)\/(day|week)$/, list],
[/^(movie|tv)\/\d+$/, details]
];
const trim = (path: string, payload: unknown) => {
if (!payload || typeof payload !== 'object') return payload;
const [, trimmer = identity] = trimmers.find(([pattern]) => pattern.test(path)) || [];
const cleanPath = path.replace(/^\//, '');
const [, trimmer = identity] = trimmers.find(([pattern]) => pattern.test(cleanPath)) || [];
return trimmer(payload as Unknown);
};