pokedex-promise-v2

repository·master·Indexed 20 days ago

https://github.com/pokeapi/pokedex-promise-v2

A Node.js wrapper for the Pokéapi v2 (version 4.3.0) that provides an interface for retrieving Pokemon information using Promises, Async/Await, or Callbacks. The library is pure ESM and includes a Pokedex client for fetching data on Pokemon, moves, items, locations, and more, with support for pagination via offset and limit.

Tokens
9.8K
Snippets
62
Records
79
Agent score
69%

What's inside pokedex-promise-v2

  1. Understand the generator pipeline

    master

    The generator/ directory contains maintainer-only code used to produce the public artifacts of pokedex-promise-v2 from upstream PokeAPI JSON Schemas. The pipeline consists of four main stages executed via npm run generate:all:

    1. apidata: Clones, syncs, or replaces the raw API data in ./api-data/.
    2. generate:types (TypesGenerator.ts): Generates the TypeScript definitions in types/index.d.ts and the API map in dist/generator/apiMap.json.
    3. generate:main (Main.ts): Generates the core Pokedex class in src/index.ts and appends it to the type definitions.
    4. generate:jsdocs (AddJSDocs.ts): Enriches the generated types with official PokeAPI documentation descriptions.

    Note: The stages hand off data using the on-disk dist/generator/apiMap.json and the in-progress types/index.d.ts file.

    npm run generate:all
  2. How to use IDs and Names with endpoints

    master

    When calling API methods, pay attention to the method suffix:

    • ByName methods: Can accept either a string (name) or an integer (ID).
    • ById methods: Can only accept an integer (ID).

    Additionally, you can pass an array of identifiers (names or IDs) to an endpoint to retrieve data for all elements in that array.

  3. Development setup and build commands

    master

    The development environment prefers Linux and requires bash, sed, and find. Use the following npm scripts to manage the development lifecycle, including data cloning, type generation, and testing.

    npm i
    npm run apidata:clone # Only if you are building for the first time
    npm run apidata:sync # Only if you have already built once
    npm run apidata:replace
    npm run generate:types
    npm run generate:main
    npm run generate:jsdocs
    npm t
  4. Make requests using Async/Await, Promises, or Callbacks

    master

    The library supports three different asynchronous patterns:

    1. Async/Await: Use await within an async function.
    2. Promises: Use .then() and .catch().
    3. Callbacks: Pass a callback function as the last argument (response, error) => { ... }.
    // Async/Await
    (async () => {
        try {
            const golduckSpecies = await P.getPokemonSpeciesByName("golduck")
            console.log(golduckSpecies)
        } catch (error) {
            throw error
        }
    })()
    
    // Promise
    P.getPokemonByName(['eevee', 'ditto'])
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log('There was an ERROR: ', error);
      });
    
    // Callback
    P.getPokemonByName(34, (response, error) => {
        if(!error) {
          console.log(response);
        } else {
          console.log(error)
        }
      });
  5. Paginate root endpoint lists using offset and limit

    master

    For most root endpoints, you can retrieve a list of items using a corresponding get[Endpoint]List() method. To avoid high RAM usage from caching every item, you should provide a configuration object to paginate the results.

    Use the following configuration keys:

    • offset: The index of the first item to retrieve (default is 0).
    • limit: The maximum number of items to return (default is 100000).

    Warning: Do not pass a config object if you intend to fetch the entire dataset at once, as this will attempt to cache everything in your RAM.

      const interval = {
        limit: 10,
        offset: 34
      }
      P.getPokemonsList(interval)
        .then((response) => {
          console.log(response);
        })
  6. Regenerate the library artifacts

    master

    When upstream PokeAPI schemas change, use the following workflow to update the library's types and source code:

    1. Run the full generation pipeline:
      npm run generate:all
    2. Inspect the changes to ensure the rewrite pipeline handled the new schemas correctly:
      git diff types/ src/

    Post-generation review checklist:

    • New XxxElement / XxxObject names: If they have no canonical sibling, they are real types. Leave them or rename them manually.
    • Purple* / Fluffy* / Tentacled* survivors: If these weren't collapsed, it means no 'dominator' (a superset shape) was found. If they are semantically the same, add a shapeAliases entry in TypesGenerator.ts.
    • Unprocessed {url} or {name, url} shapes: This indicates a failure in Pass 1; the logic in TypesGenerator.ts needs fixing.
    • Failed deduplication: If a *Element / *Object pair didn't collapse, check if quicktype emitted a third structurally identical interface, which causes the dedupe to skip to avoid incorrect merges.
    • Unexpected any[]: If an any[] appears outside of the Evolution Chain recursion boundary, inspect the schema for empty-array artifacts.
    npm run generate:all
    git diff types/ src/
  7. Handle errors in Pokedex requests

    master
    Most methods in the client accept an optional callback function. If an error occurs during the request, the client catches the error and passes it to the callback via handleError(error, callback). If no callback is provided, the method returns a rejected Promise.
  8. Configure the Pokedex client

    master

    Pass a configuration object to the Pokedex constructor to customize the connection. If no object is provided, the client defaults to https://pokeapi.co with a 20-second timeout and an 11-day cache limit.

    Available Configuration Options:

    • protocol: The connection protocol (e.g., 'https').
    • hostName: The host address (e.g., 'localhost:443').
    • versionPath: The API version path (e.g., '/api/v2/').
    • cacheLimit: Cache duration in milliseconds.
    • timeout: Request timeout in milliseconds.
    import Pokedex from 'pokedex-promise-v2';
    const options = {
      protocol: 'https',
      hostName: 'localhost:443',
      versionPath: '/api/v2/',
      cacheLimit: 100 * 1000, // 100s
      timeout: 5 * 1000 // 5s
    }
    const P = new Pokedex(options);
  9. Fetch Location data

    master

    Retrieve information about Pokemon locations and regions:

    • getLocationByName(name): Returns data about a specific pokemon location.
    • getLocationAreaByName(name): Returns data about a specific pokemon location area.
    • getPalParkAreaByName(name): Returns data about a specific pokemon pal park area.
    • getRegionByName(name): Returns data about a specific pokemon region.
      P.getLocationByName("sinnoh")
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log('There was an ERROR: ', error);
        });