moviedb-promise

repository·main·Indexed 42 days ago

https://github.com/grantholle/moviedb-promise

A TypeScript Node.js library providing a Promise-based wrapper for The Movie Database (TMDB) V3 API. Version 4.0.8 allows developers to interact with movie and television data using async/await, manage user sessions and watchlists, and batch requests using the append_to_response option.

Tokens
7.4K
Snippets
22
Records
27
Agent score
53%

What's inside moviedb-promise

  1. Call methods with placeholders

    main

    When a method's endpoint contains placeholders (e.g., tv/:id), you can provide the required parameters in two ways:

    1. Object Syntax: Pass an object where the keys match the placeholder names. This is recommended for clarity.
    2. Single Parameter Syntax: If the method has exactly one placeholder, you can pass the value directly as a single argument.

    Note that for methods without placeholders (like searchMovie), you must pass a configuration object containing the valid query parameters defined by the TMDB API (e.g., query, language, page).

    // Using object key matching for 'tv/:id'
    moviedb.tvInfo({ id: 61888 }).then(...)
    
    // Using single parameter for 'tv/:id'
    moviedb.tvInfo(61888).then(...)
    
    // Using query parameters for 'search/movie'
    const parameters = {
      query: 'Kindergarten Cop',
      language: 'fr' // ISO 639-1 code
    }
    moviedb.searchMovie(parameters).then(...)
  2. Initialize the MovieDb class

    main

    To use the library, import MovieDb from the package and instantiate it with your TMDB API key. Note that in v2+, MovieDb is a property of the package export.

    const { MovieDb } = require('moviedb-promise')
    const moviedb = new MovieDb('your api key')
    const { MovieDb } = require('moviedb-promise')
    const moviedb = new MovieDb('your api key')
  3. Use append_to_response to batch requests

    main

    The movieInfo, tvInfo, seasonInfo, episodeInfo, and personInfo methods support the append_to_response option. This allows you to include sub-requests in a single HTTP call, improving efficiency by appending additional data to the primary response object.

    TypeScript Note: Because the appended data is not part of the default return type, you must use type casting to access the new properties safely.

    // TypeScript: Cast the response to include the appended data types
    const response = await moviedb.movieInfo({ id: tmdbId, append_to_response: "release_dates" })
      as MovieResponse & { release_dates: MovieReleaseDatesResponse }
    
    // JavaScript usage
    const res = await api.tvInfo({
      id: 4629,
      append_to_response: 'season/1,season/1/credits',
    })
  4. Manage user sessions and watchlists

    main

    For endpoints requiring an account (like watchlists), you can provide a sessionId. If you set the sessionId property on your moviedb instance, you do not need to pass an id parameter to account-specific methods.

    Workflow for obtaining a session ID:

    1. Call requestToken() to get a token.
    2. Direct the user to authorize via: https://www.themoviedb.org/authenticate/${token}.
    3. Call retrieveSession() to get the resulting session ID.
    4. Cache the session ID and assign it to moviedb.sessionId for future requests.

    Example: Accessing a watchlist with a cached session

    // Set the cached session ID
    moviedb.sessionId = 'my-cached-session-id'
    
    // Now call account methods without passing an ID
    moviedb
      .accountMovieWatchlist()
      .then((res) => {
        console.log(res)
      })
      .catch(console.error)
    // This is the same as calling it as
    // moviedb.accountMovieWatchlist({ id: '{account_id}' })
    moviedb.sessionId = 'my-cached-session-id'
    moviedb
      .accountMovieWatchlist()
      .then((res) => {
        // Your watchlist items
        console.log(res)
      })
      .catch(console.error)
  5. Use async/await with moviedb-promise

    main

    All functions in moviedb-promise return a Promise. You can use async/await syntax, provided the call is made within an async function.

    Example: Searching for a movie by title In v3+, search functions accept a string directly, which is used for the query property.

    const findMovie = async (title) => {
      // Equivalent to { query: title }
      const res = await moviedb.searchMovie(title)
      return res
    }
    const findMovie = async (title) => {
      // Equivalent to { query: title }
      const res = await moviedb.searchMovie(title)
    
      return res
    }
  6. Access Credits for Movies, TV Shows, or People

    main

    The API provides different ways to access credits depending on the entity:

    • For Movies/TV/People (General): CreditsResponse provides cast (Array<Cast>) and crew (Array<Crew>).
    • For Aggregated Data: AggregateCreditsResponse provides cast (Array<AggregateCast>) and crew (Array<AggregateCrew>), which are useful for summary views.
    • For People (Movie specific): PersonMovieCreditsResponse provides detailed cast and crew lists including specific movie metadata like release_date and vote_average for each credit.
    • For People (TV specific): PersonTvCreditsResponse provides detailed cast and crew lists including TV-specific metadata like first_air_date and episode_count.
    • For People (Combined): PersonCombinedCreditsResponse merges both movie and TV credits into single arrays of cast and crew with a media_type field to distinguish them.
  7. Manage User Lists and Account State

    main

    For authenticated users, the API supports managing personal lists and account states:

    • Lists: Use MovieList to view list details. CreateListParams allows creating new lists with a name and description. CreateListItemParams is used to add a media_id to a list.
    • Account State: MovieAccountStateResponse and ShowAccountStatesResponse indicate if a specific movie or show is a favorite, rated, or in the user's watchlist.
    • Watch Providers: WatchProviderResponse provides a mapping of streaming providers (e.g., Netflix, Disney+) by country code (e.g., US, GB). Each country contains rent, buy, flatrate, ads, or free options.
  8. Authenticate and manage sessions

    main

    The MovieDb client provides methods to handle authentication tokens and session IDs, which are required for accessing user-specific data (like ratings or watchlists).

    • requestToken(): Retrieves a new authentication token using your API key. It automatically handles token expiration by requesting a new one if the current one is expired.
    • retrieveSession(): Uses a retrieved authentication token to create and return a sessionId. Once a session is established, the client automatically includes the session_id in subsequent requests.
    const token = await movieDb.requestToken();
    const sessionId = await movieDb.retrieveSession();
    // sessionId is now stored in movieDb.sessionId and used for authenticated requests
  9. Search and Discover Movie and TV Results

    main

    When performing searches or discovery, the API returns various result types. Use these interfaces to type your response handling:

    • MovieResult: Represents a movie in search/discovery lists. Includes media_type: 'movie', title, release_date, and genre_ids.
    • TvResult: Represents a TV show in search/discovery lists. Includes media_type: 'tv', name, first_air_date, and genre_ids.
    • PersonResult: Represents a person in search/discovery lists. Includes media_type: 'person', name, and known_for (an array of MovieResult or TvResult).
    • SearchMultiResponse: A combined response containing arrays of MovieResult, TvResult, and PersonResult.

    Most paginated responses (like MovieResultsResponse, SearchPersonResponse, etc.) extend PaginatedResponse, providing page, total_results, and total_pages alongside the results array.

    // Example of handling a multi-search response
    interface SearchMultiResponse {
      results?: Array<MovieResult | TvResult | PersonResult>
    }
  10. Handle Media Images and Assets

    main

    Images are returned in various formats depending on the endpoint. Common structures include:

    • Base Image Properties: All image types (Logo, Backdrop, Profile, Poster, TitleLogo) share aspect_ratio, file_path, height, width, vote_average, and vote_count.
    • Movie/TV Images: MovieImagesResponse and TvImagesResponse return categorized arrays: backdrops, posters, and logos.
    • Person Images: PersonImagesResponse returns an array of profiles.
    • Episode Images: EpisodeImagesResponse returns an array of stills (using the EpisodeImage type).

    To construct a full URL, you typically combine the base_url from the ConfigurationResponse with the file_path from the image object.

  11. Initialize the MovieDb client

    main

    To use the library, instantiate the MovieDb class with your TMDB API key. You can optionally specify a custom baseUrl and a requestsPerSecondLimit to manage rate limiting via an internal throttle mechanism.

    Constructor Parameters:

    • apiKey (string): Your TMDB API key.
    • baseUrl (string, optional): The base URL for the API. Defaults to https://api.themoviedb.org/3/.
    • requestsPerSecondLimit (number, optional): The maximum number of requests allowed per second. Defaults to 50.
    import { MovieDb } from 'moviedb-promise';
    
    const movieDb = new MovieDb('YOUR_API_KEY');
    // Or with custom config
    const movieDbCustom = new MovieDb('YOUR_API_KEY', 'https://api.themoviedb.org/3/', 20);