3. Fetching
3.1 Retrieving a single Pokemon
Use the get
method to fetch a single instance of an entity:
import { get } from '@42.nl/spring-connect';
const POKEMON_API_URL = '/api/pokemon';
type Pokemon = {
id: number;
name: string;
};
function onePokemon(id: number) {
return get<Pokemon>(`${POKEMON_API_URL}/${id}`);
}
const bulbasaur = await onePokemon(42);
Optionally you can add a second parameter to define the query parameters:
/* GET api/pokemon/1?active=true */
function activePokemon(id: number) {
return get<Pokemon>(`${POKEMON_API_URL}/${id}`, { active: true });
}
const bulbasaur = await activePokemon(42);
3.2 Retrieving a page of Pokemon
The Page could be used for endpoints that return a Spring page:
/* GET api/pokemon?page=1 */
function pageOfPokemon(page: number) {
return get<Page<Pokemon>>(POKEMON_API_URL, { page });
}
const page = await pageOfPokemon(1);
3.3 Retrieving a list of Pokemon
We recommended using the
page
method whenever possible as it gives you more flexibility and is more memory efficient.
To retrieve a list of Pokémon:
/* GET api/pokemon?limit=10 */
function listAllPokemon() {
return get<Pokemon[]>(POKEMON_API_URL);
}
const pokemons = await listOfPokemon();
Useful when retrieving a fixed set of data with limited items.
3.5 Page vs List
Prefer page
over list
when possible because it is more memory efficient
to load only a single slice of the data at a time.
It must also be noted that it is very unlikely that a REST endpoint
supports both page
and list
at the same time. So use the variant
which your back-end exposes.