Git Product home page Git Product logo

pokenode-ts's Introduction

Pokenode-ts

Pokenode-ts is a lightweight Node.js wrapper for the PokéAPI with built-in types. It provides an easy way to integrate your application with the PokéAPI.

Features

  • 🛠️ Built-in typings: TypeScript support with pre-defined types.
  • 📦 Axios with auto-cache requests: Efficiently manage API requests with automatic caching.
  • 🌲 Logging: Easily log and track your API interactions.

Installation

# NPM
npm install axios axios-cache-interceptor pokenode-ts

# Yarn
yarn add axios axios-cache-interceptor pokenode-ts

# Pnpm
pnpm add axios axios-cache-interceptor pokenode-ts

Basic Example

Using a client, like PokemonClient:

import { PokemonClient } from 'pokenode-ts';

(async () => {
  const api = new PokemonClient();

  try {
    const pokemonData = await api.getPokemonByName('luxray');
    console.log(pokemonData.name); // Outputs "Luxray"
  } catch (error) {
    console.error(error);
  }
})();

Or, using the MainClient:

import { MainClient } from 'pokenode-ts';

(async () => {
  const api = new MainClient();

  try {
    const pokemonData = await api.pokemon.getPokemonByName('luxray');
    console.log(pokemonData.name); // Outputs "Luxray"
  } catch (error) {
    console.error(error);
  }
})();

Documentation

Check out our Documentation page!

Security

Every change in this project is analyzed by SonarCloud

Quality Gate Status Bugs Code Smells Quality Gate Status codecov

Leave your feedback

Donate

If pokenode-ts is valuable to you, please consider buying me a coffee ❤️

Analytics

pokenode-ts's People

Contributors

alex-pex avatar caneon28 avatar dependabot[bot] avatar elikeith404 avatar gabb-c avatar menewman avatar moyzlevi avatar mrkarbrador avatar nathonius avatar njs-guy avatar scotteroberts avatar seiryokusan avatar semantic-release-bot avatar simonorono avatar taiwoo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

pokenode-ts's Issues

Issues with peer dependencies found (axios version from axios-cache-adapter)

What version of pokenode-ts are you using?

1.13.0

What version of Node.js are you using?

16.13.0

What operating system are you using?

macOS

Describe the Bug

When we install the project, pnpm block the process due to this peer-dependency issue :

image

Expected Behavior

No peer-dependency issue 😄.

To Reproduce

Execute command pnpm i pokenode-ts.

Rollup Build

Describe the feature you'd like to request

Use Rollup to build:

  • CommonJS
  • ES Modules
  • Typings

Describe the solution you'd like

// rollup.config.js

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from 'rollup-plugin-typescript2';
import dts from 'rollup-plugin-dts';
import del from 'rollup-plugin-delete';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';

import { terser } from 'rollup-plugin-terser';

import * as packageJson from './package.json';

/** @type {import('rollup').RollupOptions} */
const config = [
  {
    input: 'src/index.ts',
    output: [
      // commonjs
      {
        file: packageJson.main,
        format: 'cjs',
        sourcemap: true,
      },
      // esmodule
      {
        file: packageJson.module,
        format: 'esm',
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal(), // automatically externalize peerDependencies in a rollup bundle
      resolve(), // locates modules using the Node resolution algorithm
      commonjs(), // convert CommonJS modules to ES6
      typescript({ useTsconfigDeclarationDir: true, tsconfig: './tsconfig.json', clean: true }), // integration between rollup and typescript
      terser(), // minify generated es bundle (uses terser under the hood)
    ],
  },
  // typings
  {
    input: 'lib/types/index.d.ts',
    output: [{ file: 'lib/index.d.ts', format: 'esm' }],
    plugins: [dts(), del({ targets: 'lib/types', hook: 'buildEnd' })], // roll-up .d.ts files and delete the types dir
  },
];

export default config;
$ yarn add --dev rollup rollup-plugin-typescript2 @rollup/plugin-node-resolve @rollup/plugin-commonjs rollup-plugin-dts rollup-plugin-delete rollup-plugin-peer-deps-external rollup-plugin-terser

Describe alternatives you've considered


Fix Sonar code smells

What version of pokenode-ts are you using?

latest

What version of Node.js are you using?

lts/hydrogen

What operating system are you using?

Windows 11

Describe the Bug

Fix code smells pointed by Sonarcloud analysis

Expected Behavior

No code smells

To Reproduce

Open Pokenode-ts Sonarcloud

Possible typo in documentation for cacheing

What version of pokenode-ts are you using?

1.17.0

What version of Node.js are you using?

18.12.1

What operating system are you using?

Windows

Describe the Bug

Screenshot (18)

Great job so far! Gabb.

I have a documentation issue while reading the cache section, from the part highlighted in the image above, is it meant to be "localStorage"?

I hope I used the right issue template for this.

Expected Behavior

The right spelling of "localStorage" for clear understanding of docs 🙂

To Reproduce

Visit this section of the docs here 🙂

"Edit this page on GitHub" links in documentation are broken

What version of pokenode-ts are you using?

1.20.0

What version of Node.js are you using?

20.6.1

What operating system are you using?

Windows 11

Describe the Bug

I found a content issue in the documentation, but when I clicked the "Edit this page on GitHub" link, I get directed to a page that merely says "Not Found". I tried editing some other pages in order to see if this was an issue with only one specific page, and all give me the same error. (For clarity I'm leaving out the actual content issue and focusing on the bug with the documentation system.)

The original page I had the issue with was:
https://pokenode-ts.vercel.app/clients/pokemon-client

The link to edit goes to this url:
https://github.com/Gabb-c/pokenode-ts/vitepress/edit/main/docs/src/clients/pokemon-client.md

Expected Behavior

When clicking the link, I would expect be taken to an editor for the documentation.

To Reproduce

Go to https://pokenode-ts.vercel.app/clients/pokemon-client and click the "Edit this page on GitHub" link.

NamedAPIResourceList doesn't allow access to Pokemon's name in results

What version of pokenode-ts are you using?

1.13.0

What version of Node.js are you using?

14.17.3

What operating system are you using?

MacOS

Describe the Bug

When using the NamedAPIResourceList interface, I cannot access the Pokemon's name (e.g. pokemon.name) in the result array when getting a list of Pokemon (using listPokemons).

This appears to be due to the results in NamedAPIResourceList having a union type of NamedAPIResource[] | APIResource[]; rather than just NamedAPIResource[] as mentioned in the documentation.

TS error: Property 'name' does not exist on type 'APIResource'.

Documentation: https://pokenode-ts-docs-gabb-c.vercel.app/docs/typings/common-typings#named-api-resource-list

Currently when viewing in node_modules/pokenode-ts/dist/index.d.ts :

export interface NamedAPIResourceList {
	/** The total number of resources available from this API */
	count: number;
	/** The URL for the next page in the list */
	next: string | null;
	/** The URL for the previous page in the list */
	previous: string | null;
	/** A list of named API resources */
	results: NamedAPIResource[] | APIResource[];
}

### Expected Behavior

const api = new PokemonClient();

api.listPokemons(0, 500)
        .then((pokeData) => {
            console.log(pokeData)
            pokeData.results.filter((pokemon) => {
                return pokemon.name === 'ditto'
            })
        })
        .catch((error) => {
            console.log('err')
        })

pokemon.name should be accessible, it can be seen in the data returned.

### To Reproduce

const api = new PokemonClient();

api.listPokemons(0, 500)
        .then((pokeData) => {
            console.log(pokeData)
            pokeData.results.filter((pokemon) => {
                return pokemon.name === 'ditto'
            })
        })
        .catch((error) => {
            console.log('err')
        })

pokemon.name is throwing a TS error. Exact error: Property 'name' does not exist on type 'APIResource'. Only pokemon.url is accessible.

Have the ability to specify the base URL as a client option

Describe the feature you'd like to request

I'd like to be able to use my local instance of the PokeAPI with this library.

For the app I'm creating, I use the PokeAPI to generate data files during development time. To avoid making lots of calls to the PokeAPI, I host a local instance of it. I would like to use this library with my local instance of the PokeAPI.

Describe the solution you'd like

I believe that adding the base URL as an optional parameter to the ClientArgs interface would be the best solution and, if empty, use BaseURL.REST.

Describe alternatives you've considered

I created a wrapper class around MainClient that replaced the api instance of each client with my own:

import { ClientArgs, MainClient } from "pokenode-ts"
import { setup } from 'axios-cache-adapter';

export class CustomClient extends MainClient {
  constructor(clientArgs?: ClientArgs) {
    super(clientArgs);

    [
      this,
      this.berry,
      this.contest,
      this.encounter,
      this.evolution,
      this.game,
      this.item,
      this.location,
      this.machine,
      this.move,
      this.pokemon,
    ].forEach(_ => _.api = setup({
        baseURL: 'http://localhost/api/v2',
        headers: {
          'Content-Type': 'application/json',
        },
        cache: {
          maxAge: clientArgs?.cacheOptions?.maxAge || 0,
          ...clientArgs?.cacheOptions,
        },
      })
    )
  }
}

If the proposal is accepted, I could code the feature.

Missing type in Emerald interface

What version of pokenode-ts are you using?

next

What version of Node.js are you using?

17.0.1

What operating system are you using?

macOS

Describe the Bug

There is a key-value pair missing from the [src/models/Pokemon/pokemon.ts]/Emerald interface.

Expected Behavior

File: src/models/Pokemon/pokemon.ts
Line: 340

The key front_shiny is missing under the description.

To Reproduce

Open file src/models/Pokemon/pokemon.ts and scroll to line 340.

Wrong `evolution_detail` key in `ChainLink` interface

What version of pokenode-ts are you using?

1.13.1

What version of Node.js are you using?

14.19.0

What operating system are you using?

WIindows

Describe the Bug

Wrong evolution_detail key in ChainLink interface.

Expected Behavior

Change to evolution_details instead.

To Reproduce

Not thing.

Combat simulation

Describe the feature you'd like to request

Add a method to simulate a combat between pokémons.

Describe the solution you'd like

Not applicable

Describe alternatives you've considered

Not applicable

Pokedex Entry treats pokemons_species as NamedApiResource[]

What version of pokenode-ts are you using?

1.13.2

What version of Node.js are you using?

16.5.1

What operating system are you using?

Linux(Ubuntu)

Describe the Bug

Pokedex Entry treats pokemon_species as NamedApiResource Array (or NamedApiResource[]). Trying to map the pokemon_species results in "pokemon_species.map() is not a function" in browser console, and trying to get name or url directly from pokemon_species results in a error of typing on Workspace

This is what happens if you ignore the warnings

image

Expected Behavior

As pokemon_species in Pokemon Entry only have name and url as attributes, it was expected to get an Object instead of an array

To Reproduce

First you get a Pokedex data, then you map or select a position in the pokemon_entries array. Inside of the entry, try to get the name or the url of pokemon_species

Get all Pokemons by generation

Describe the feature you'd like to request

I'd like to request a feature that can retrieve all pokemons from the poke-api that belong to the same generation. Like getting all the pokemons of generation III or II. Currently the poke-api doesn't have this feature, but it would be nice to ease a pokedex-like web app.

Describe the solution you'd like

The only solution I can think of is doing a request of all 1200 pokemons from the api and after that, filtering the array to return only the pokemons of the specific generation.

Describe alternatives you've considered

There are no alternatives.

Auto caching doesn't seem to work

What version of pokenode-ts are you using?

1.19.1

What version of Node.js are you using?

18.12.1

What operating system are you using?

Windows

Describe the Bug

The docs say that caching is enabled by default. But no matter what I try, it never seems to save to the cache.

Expected Behavior

The Client should save the data to the browser cache.

To Reproduce

This Svelte component just makes a basic API call and logs the result.

<script lang="ts">
  import { PokemonClient } from "pokenode-ts";

  async function onClick() {
    const api = new PokemonClient({ logs: true });

    await api
      .getPokemonByName("luxray")
      .then((data) => console.log(data.name)) // will output "Luxray"
      .catch((error) => console.error(error));
  }
</script>

<main>
  <button on:click={onClick}>Press</button>
</main>

This is the console log after the button is pressed:

[ Request Config ] GET | /pokemon/luxray
index.mjs:14 [ Response ] STATUS 200 | NOT CACHED
luxray

I double checked the browser cache and sure enough, it doesn't save. I'm not sure what's gone wrong. I even copy and pasted the example from the cache page and it doesn't cache either. I also have Axios v1.4.0 and axios-cache-interceptor v1.19.1 installed in the same project.

Limit & offset not working on ListPokemon API using React Native

What version of pokenode-ts are you using?

1.19.0

What version of Node.js are you using?

18.15.0

What operating system are you using?

macOS 13.3.1

Describe the Bug

I used ListPokemon() API using PokemonClient and it worked well without parameters. But when I passed in 2 params which are limit and offset, the result was exactly the same. And I found out that the problem only occurs when I use with React Native. It sent out a request looks like this:
image

Here is the cURL that is created from the captured request:

curl -H "accept:application/json, text/plain, */*" -H "cache-control:no-cache" -H "pragma:no-cache" -H "expires:0" https://pokeapi.co/api/v2/pokemon?_searchParams%5B0%5D%5B0%5D=offset&_searchParams%5B0%5D%5B1%5D=80&_searchParams%5B1%5D%5B0%5D=limit&_searchParams%5B1%5D%5B1%5D=40

Expected Behavior

It should return a new list of pokemon with new offset and new limit

To Reproduce

  1. Initialize a react native project with this instruction
  2. Install this dependency following the instructions in README.md
  3. Using the pokemon client as below:
const pokemonApi = new PokemonClient();
const pokemonList = pokemonApi.listPokemons(20, 20);

Why is `baseURL` unset in `getResourceByUrl`?

Discussed in #887

Originally posted by nitwhiz August 13, 2023
getResourceByUrl requests without the base-url set in the client used for this request. Why is it designed this way?

return new Promise<T>((resolve, reject) => {
this.api
.get(url, { baseURL: "" })
.then((response: AxiosResponse<T>) => resolve(response.data))
.catch((error: AxiosError<string>) => reject(error));

This makes it hard to use this client with a selfhosted instance of the PokeAPI JSON-files, where following the urls in the responses is necessary.

Better built-in logger

Describe the feature you'd like to request

A build-in development and production ready logger with levels, transports and custom formats.

Describe the solution you'd like

Something like Winston

Describe alternatives you've considered

Something like Winston

Testing issue labeler

What version of pokenode-ts are you using?

1.4.0

What version of Node.js are you using?

14.16.0

What operating system are you using?

I use Arch btw

Describe the Bug

Nothing works

Expected Behavior

just testing

To Reproduce

not applicable

"Generation" is spelt "Generaton" in Move interface

What version of pokenode-ts are you using?

1.13.0

What version of Node.js are you using?

14.17.3

What operating system are you using?

MacOS

Describe the Bug

"generation" is spelt "generaton" in Move interface. This causes a mismatch in the data incoming from the API as the object property is actually called "generation".

Expected Behavior

I should be able to access the move data with move.generation.

To Reproduce

Instead I get the following error telling me to use 'generaton' instead.

Property 'generation' does not exist on type 'Move'. Did you mean 'generaton'?ts(2551)
[index.d.ts(2089, 2): ]()'generaton' is declared here.

Add others interface to pokemon sprites interface

Describe the feature you'd like to request

I like using your lib for my pet project but I can't use other world images via sprites. in sprites interface there are not have any others sprites.Cause of that I add other type to Sprites interface

Describe the solution you'd like

Add some columns to sprites interface

Describe alternatives you've considered

add others?:[] to sprites interface

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.