@xcoder143_x/tmdb-api
v1.1.2
Published
TMDB API client for nflix
Readme
@xcoder143_x/tmdb-api
A lightweight, fully typed, promise-based API client for The Movie Database (TMDB). This package provides an easy way to fetch movies, TV shows, and search data from the TMDB API, and includes robust mappers to integrate perfectly with Next.js and MongoDB.
Features ✨
- Fully Typed: Built with TypeScript. Includes types for movies, TV shows, seasons, episodes, and search results.
- Built-in Proxy Fallback: Securely fetch TMDB data directly from the browser (bypassing CORS) using automatic proxy chains.
- In-Memory Caching: Optional caching with configurable Time-To-Live (TTL) to avoid hitting TMDB rate limits.
- Nflix Mappers: Built-in mappers to easily convert raw TMDB data into your specific database schema.
- Robust Error Handling: Custom
TmdbApiErrorclass for easytry...catchdebugging. - Image URL Formatters: Helpers to generate exact URLs for posters, backdrops, and profiles in any size.
Installation
npm install @xcoder143_x/tmdb-apiInitialization & API Keys 🔑
The TmdbClient requires your TMDB API Key as a strict first parameter.
Because it accepts the key dynamically via the constructor (rather than hardcoding it to process.env.TMDB_API_KEY), this package perfectly supports architectures where the API key is fetched dynamically from a database (like an Admin Settings panel) rather than static .env files.
import { TmdbClient } from "@xcoder143_x/tmdb-api";
// Example A: Simple .env initialization
const tmdbEnv = new TmdbClient(process.env.TMDB_API_KEY!);
// Example B: Dynamic Database Initialization (e.g. Next.js API Route)
const settings = await db.collection("settings").findOne({ _id: "global" });
const apiKey = settings.tmdbKey;
const tmdb = new TmdbClient(apiKey, {
cache: true, // Enable in-memory caching
ttl: 300, // Cache expiration time in seconds (5 mins)
useProxies: true // Enable automatic CORS proxy chain (perfect for browser-side fetching!)
});Core API Methods
Fetching Content
All fetching methods automatically append credits,videos,images by default unless specified otherwise.
// Fetch Movie
const movie = await tmdb.getMovie(299534); // Avengers: Endgame
// Fetch TV Show
const tvShow = await tmdb.getTvShow(1399); // Game of Thrones
// Fetch TV Show with Deep Seasons Data (Appends all episodes for Season 1 & 2)
const deepTvShow = await tmdb.getTvShow(1399, "credits,videos,images,season/1,season/2");
// Fetch specific Season
const season = await tmdb.getSeason(1399, 1);Searching & Discovering
// Search specific types
const movies = await tmdb.searchMovies("Avengers");
const shows = await tmdb.searchTv("Breaking Bad");
// Search everything (Multi)
const results = await tmdb.searchMulti("Inception");
// Trending Content
const trending = await tmdb.getTrending("all", "week");
// Browse by Genre
const scifiMovies = await tmdb.getMoviesByGenre(878);Nflix Content Mappers 🔄
This package includes a powerful utility to automatically map raw, messy TMDB JSON data perfectly into your database's MappedContent schema.
import { tmdbMovieToContent, tmdbTvToContent } from "@xcoder143_x/tmdb-api";
const rawTmdbData = await tmdb.getMovie(157336);
// Maps TMDB data to include trailerUrls, transparent logos, desktop/mobile billboards, and top 25 cast!
const readyToSaveData = tmdbMovieToContent(rawTmdbData);
// For TV shows, it maps detailed `seasonsData` if included in the append_to_response!
const readyToSaveTvData = tmdbTvToContent(rawTmdbTvData); Image Formatting
The client has built-in helpers to easily format poster, backdrop, and profile paths.
const posterUrl = tmdb.formatPosterUrl(movie.poster_path, "w500");
// -> https://image.tmdb.org/t/p/w500/...
const backdropUrl = tmdb.formatBackdropUrl(movie.backdrop_path, "w1280");
// -> https://image.tmdb.org/t/p/w1280/...
const profileUrl = tmdb.formatProfileUrl(actor.profile_path, "h632");
// -> https://image.tmdb.org/t/p/h632/...Database Integration & Schemas 🗄️
This package ships with production-ready database schemas so you don't have to write any boilerplate code. We support the most popular ORMs via optional peer dependencies.
1. Zod (API Validation)
Use the Zod schema to validate incoming API requests before saving them.
import { ZodContentSchema } from "@xcoder143_x/tmdb-api";
// Validates the mapped content shape
const parsedData = ZodContentSchema.parse(readyToSaveData);2. Mongoose (MongoDB)
We export a pre-built Mongoose Schema perfectly aligned with our content mappers.
import mongoose from "mongoose";
import { MongooseContentSchema } from "@xcoder143_x/tmdb-api";
export const ContentModel = mongoose.models.Content || mongoose.model("Content", MongooseContentSchema);
// Save directly to MongoDB
await ContentModel.create(tmdbMovieToContent(rawTmdbData));3. Drizzle ORM (PostgreSQL & MySQL)
We export contentTablePg for PostgreSQL and contentTableMySql for MySQL ready for your Drizzle database setup.
import { db } from "./your-db-setup";
import { contentTableMySql } from "@xcoder143_x/tmdb-api"; // or contentTablePg
await db.insert(contentTableMySql).values(tmdbMovieToContent(rawTmdbData));4. Prisma
Since Prisma uses a custom .prisma file, we export raw string templates you can copy. We have templates for PostgreSQL and MySQL/SQLite.
import { PRISMA_SCHEMA_TEMPLATE_PG, PRISMA_SCHEMA_TEMPLATE_MYSQL } from "@xcoder143_x/tmdb-api";
console.log(PRISMA_SCHEMA_TEMPLATE_MYSQL); // Copy this output into your schema.prismaError Handling
The package uses a custom TmdbApiError class that exposes the TMDB status code, making it easy to catch 404s or 401s.
import { TmdbApiError } from "@xcoder143_x/tmdb-api";
try {
const result = await tmdb.getMovie(999999999);
} catch (error) {
if (error instanceof TmdbApiError) {
console.error(`TMDB Error ${error.statusCode}: ${error.statusMessage}`);
// Output: TMDB Error 404: The resource you requested could not be found.
}
}License
MIT
