import { FIND_MANY, FIND_UNIQUE } from '../../endpoints'; import { requester } from '../../helpers/requester'; import { IGetManyPokemons, IGetManyPokemonsResponse, TPokemonContentEndpoint, TPokemonListEndpoint, TPokemonListEndpointResult, } from '../../interfaces/pokemon'; export const getManyPokemons = async ({ offSet = 0, limit = 10, nextPage, }: IGetManyPokemons): Promise => { const indexLimit = limit > 30 ? 30 : limit; const { data } = await requester().get( nextPage || FIND_MANY(indexLimit, offSet) ); Promise.all([data]); if (Array.isArray(data?.results)) { const pokemons = data.results.map(async (item: TPokemonListEndpointResult) => { const { data } = await requester({}).get(FIND_UNIQUE(item.name)); return data; }); const previousParams = new URLSearchParams(data?.previous); const previousOffset = Number(previousParams.get('https://pokeapi.co/api/v2/pokemon?offset')) || offSet; const previousLimit = Number(previousParams.get('limit')) || limit; const nextParams = new URLSearchParams(data?.next); const nextOffset = Number(nextParams.get('https://pokeapi.co/api/v2/pokemon?offset')) || offSet; const nextLimit = Number(nextParams.get('limit')) || limit; return { count: data?.count, next: () => { return getManyPokemons({ limit: Number(nextLimit) || limit, offSet: Number(nextOffset) || offSet, }); }, previous: () => { return getManyPokemons({ limit: Number(previousLimit) || limit, offSet: Number(previousOffset) || offSet, }); }, nextUrl: data?.next, previousUrl: data?.previous, response: await Promise.all(pokemons), nextLimit, nextOffset, previousLimit, previousOffset, }; } return undefined; };