npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@markmccoid/tmdb_api

v0.3.3

Published

Wrapper for the TMDB Api

Downloads

158

Readme

TMDB API Wrapper

This package wraps select API calls from the TMDB API. To use this, you will need to get an API Key from The Movie Database website.

Motivation

This project was inspired when writing another application that accessed the TMDB API for TV data. I found that I wrote a bunch of functions to get the data and then had to curate the return data into something useful. It seemed to make sense to package all this logic into a single package that could be included in any other project.

Realize that the TMDB API is HUGE! So, my goal was to encapsulate the most common data that a (my) project would need. If data is missing that you need, do a pull request and add it!

Install

$ yarn add @markmccoid/tmdb_api
## OR
$ npm install @markmccoid/tmdb_api

API Docs

The API Docs will help you navigate the functions available. https://markmccoid.github.io/tmdb_api/

NOTE: The generated docs for the functions are going to be superseded by the TypeScript type annotations.

You will find that there are two main types of data returned. Either Raw or Curated.

Raw API functions are simply calls to the main API endpoints, returning all data from them.

Curated API functions take the Raw data and format it in a way to make it easier to use and manipulate.

The Raw and Curated functions are split into Common, TV and Movie functions. TV and Movie are self explanatory. The Common functions are those that span both TV and Movies. These will include Person data.

Lastly, there is a section of Helpers functions. You most likely will not need these if you are using the Curated functions.

I've also tried to include typedefs for the curated functions so will have some documentation on what information is returned with each call.

Initialize

Before you can call the API functions you will need to initialize the module with your API Key using the initTMDB(APIKey, [options]) function. The options object is optional.

import React from "react";
import Main from "./components/Main";
import { initTMDB } from "@markmccoid/tmdb_api";

function App() {
  const [isLoaded, setIsLoaded] = React.useState(false);

  React.useEffect(() => {
    const initializeApp = async () => {
      const tmdbConfig = await initTMDB("0e4935axxxxxxxxxxxxxxxxxx");
      setIsLoaded(true);
    };
    initializeApp();
  }, []);

  if (!isLoaded) {
    return <div>Initializing App...</div>;
  }
  return (
    <div>
      <header>TMDB API Wrapper</header>
      <Main />
    </div>
  );
}

export default App;

initTMDB returns a config object that contains the config information used in the application. You probably won't need it.

interface TMDBConfig {
  IMG_URL: string;
  SECURE_IMG_URL: string;
  API_KEY: string;
  TV_GENRE_OBJ: { [key: number]: string };
  MOVIE_GENRE_OBJ: { [key: number]: string };
  API_OPTIONS: {
    dateFormatString: string;
  };
}

Options Object

When initializing, you also have the options to pass an Options object. This will set some defaults for how this package will return your data and query the TMDB api.

  • dateFormatString
{
  dateFormatString: "MM-dd-yyyy";
}

The dateFormatString must use the formatting options from the date-fns package.

  • defaultAPIParams
{
  defaultAPIParams: {
    include_adult: false;
  }
}

The defaultAPIParams object currently allows you to change the "include_adult" flag. If not passed, the default is "false".

Raw API Functions

The Raw API functions are functions that call and return the data directly from the TMDB API endpoints. This is in contrast to the Curated API functions, which do some additional formatting like returning full image URLs.

All Raw API functions return data in the following object shape:

{
    data: // The meat of the return from TMDB API call.
    apiCall: <string> // apicall used to get results
}

Error Object

If an error should occur, all Raw API functions return a standard error object in the following shape:

{
    error: err, // The full error object
    status: err.response ? err.response.request.status : null,
    statusText: err.response ? err.response.request.statusText : null,
    apiCall: err.response
      ? err.response.request.responseURL
      : err.config
      ? err.config.url
      : null
  }

Note: In raw functions, the full image path is not returned as it is in the curated functions. Refer to TMDB API for Image for details. You can use the getConfig() function to get the config details.

Curated API Functions

Curated functions are wrappers around the Raw API calls. They do some extra work so you don't have too.

  1. Resolve any images to full image paths.

  2. Convert date strings to an JavaScript Object in the form

    {
      date, // JavaScript date
        epoch, // Unix timestamp -- Seconds from 1/1970
        formatted; //Formatted based on the dateFormatString passed in initTMDB() function. Default "MM-dd-yyyy"
    }
  3. Convert genre Ids to genre names (unless you are calling the genre function to get a list of id/genre combinations.)

  4. Return a curated set of items from the call.

The returned object shape is the same as the Raw calls:

{
    data: // The meat of the return from TMDB API call.
    apiCall: <string> // apicall used to get results
    page: <int> // ONLY returned for functions with a page argument
    totalResults: <int> // ONLY returned for functions with a page argument
    totalPages: <int> // ONLY returned for functions with a page argument
}

Note: for functions that have a page argument, the data object will also include, at the root of the returned object, a page (current page you are on), totalResults (total count of results), totalPages (total number of pages) properties. You will need this data for pagination.

TypeScript

My first go at using TypeScript in a project, so any comments would be appreciated.

The type definition files (*.d.ts) are located in the ./types directory and follows the same directory structure as the source files.

The Curated functions have a return type that is made up of a Base type so that the main results can have a separate type that you can use in your applications if needed.

For example, most curated functions return one of two differenct structures where the result data is in a separate key:

// -- Results that when queried will have multiple pages
{
  data: CustomType; // The meat of the return from TMDB API call.
  apiCall: string; // apicall used to get results
  page: number; // ONLY returned for functions with a page argument
  totalResults: number; // ONLY returned for functions with a page argument
  totalPages: number; // ONLY returned for functions with a page argument
}

// -- Results that are returned all in the single query
{
  data: CustomType; // The meat of the return from TMDB API call.
  apiCall: string; // apicall used to get results
}

Since multiple functions will be returning this shape, I've create two Generics to handle these.

export type BaseSinglePage<T> = {
  data: T;
  apiCall: string;
};

export type BaseMultiPage<T> = {
  data: {
    page: number;
    totalResults: number;
    totalPages: number;
    results: T;
  };
  apiCall: string;
};

What this means is that you can pull in the T type to type the actual data/results that you will most likely be using in your application.

For example, tvGetShowDetails(showId) returns the TVShowDetailsBase type, but is built using the BaseSinglePage generic passing in the TVShowDetails type, which ends up typeing the data portion of the return object:

function tvGetShowDetails(showId: number): Promise<TVShowDetailsBase>;

//-- Base built here
export type TVShowDetailsBase = BaseSinglePage<TVShowDetails>;

//-- Which results in this
type TVShowDetailsBase = {
  data: TVShowDetails;
  apiCall: string;
};

Both tvSearchByTitle and tvGetPopular return the BaseMultiPage generic:

export function tvSearchByTitle(searchValue: string, page?: number): Promise<TVSearchResultBase>;

export function tvGetPopular(page?: number, language?: string): Promise<TVSearchResultBase>;

//-- Base built here
export type TVSearchResultBase = BaseMultiPage<TVSearchResultItem[]>;

//-- Which results in this
type TVSearchResultBase = {
  data: {
    page: number;
    totalResults: number;
    totalPages: number;
    results: TVSearchResultItem[];
  };
  apiCall: string;
};