Remove pagination fetching in pokeApi.ts

develop
Jason Zhu 2023-05-19 23:28:36 +10:00
parent bde86898e2
commit 768c84d6b8
1 changed files with 3 additions and 72 deletions

View File

@ -1,92 +1,23 @@
import { import { fetchBaseQuery, createApi } from '@reduxjs/toolkit/query/react';
fetchBaseQuery,
FetchArgs,
createApi,
BaseQueryApi,
} from '@reduxjs/toolkit/query/react';
import { import {
RegionListResponseData, RegionListResponseData,
TypeListResponseData, TypeListResponseData,
PokemonResponseData, PokemonResponseData,
EvolutionChainResponseData, EvolutionChainResponseData,
PokemonSpeciesResponseData, PokemonSpeciesResponseData,
nameUrlPair,
} from 'types/api'; } from 'types/api';
export interface pokeApiFullListFetchArgs extends FetchArgs {
fetchAllPages?: boolean;
}
interface PokeAPIPaginatedResponse {
count: number;
next: string | null;
previous: string | null;
results: nameUrlPair[];
}
export const getIdFromUrl = (url: string) => { export const getIdFromUrl = (url: string) => {
const urlParts = url.split('/'); const urlParts = url.split('/');
return parseInt(urlParts[urlParts.length - 2]); return parseInt(urlParts[urlParts.length - 2]);
}; };
async function fetchAllPages(url: string | null) {
const allResults: nameUrlPair[] = [];
while (url) {
const response = await fetch(url);
const data = (await response.json()) as PokeAPIPaginatedResponse;
allResults.push(...data.results);
url = data.next;
}
return allResults;
}
export const paginationBaseQuery = (baseUrl: string) =>
fetchBaseQuery({ baseUrl });
export const pokeApiAllPagesCustomBaseQuery = async (
args: pokeApiFullListFetchArgs,
api: BaseQueryApi,
extra: any,
baseUrl: string,
) => {
const result = await paginationBaseQuery(baseUrl)(args, api, extra);
if (result.data && args.fetchAllPages) {
const data = result.data as PokeAPIPaginatedResponse;
if (data.next) {
const allResults = await fetchAllPages(data.next);
data.results = data.results.concat(allResults);
}
result.data = {
count: data.count,
results: data.results,
};
}
return result;
};
export const pokeApiBaseQuery = async (
args: pokeApiFullListFetchArgs,
api: BaseQueryApi,
extra: any,
) => {
const baseUrl = 'https://pokeapi.co/api/v2/';
if (args.fetchAllPages) {
return pokeApiAllPagesCustomBaseQuery(args, api, extra, baseUrl);
} else {
return fetchBaseQuery({ baseUrl })(args, api, extra);
}
};
export const pokeApi = createApi({ export const pokeApi = createApi({
reducerPath: 'pokeApi', reducerPath: 'pokeApi',
baseQuery: pokeApiBaseQuery, baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
endpoints: builder => ({ endpoints: builder => ({
getTypeList: builder.query<TypeListResponseData, void>({ getTypeList: builder.query<TypeListResponseData, void>({
query: () => ({ url: 'type', fetchAllPages: true }), query: () => ({ url: 'type' }),
transformResponse: (response: RegionListResponseData) => { transformResponse: (response: RegionListResponseData) => {
return { return {
...response, ...response,