feat: implemented poke api client with cache

This commit is contained in:
Stevan Freeborn
2026-07-28 07:34:17 -05:00
parent c78ff443a6
commit 68b34ec28f
5 changed files with 399 additions and 2 deletions
+67 -2
View File
@@ -4,10 +4,17 @@ import (
"fmt"
"os"
"sort"
"time"
"github.com/StevanFreeborn/pokedexcli/internal/pokeapi"
"github.com/StevanFreeborn/pokedexcli/internal/pokecache"
)
type context struct {
commands map[string]cliCommand
commands map[string]cliCommand
client *pokeapi.Client
prevOffset int
nextOffset int
}
func (r *context) register(c cliCommand) {
@@ -29,12 +36,29 @@ func NewContext() *context {
callback: commandHelp,
}
var mapCommand = cliCommand{
name: "map",
description: "Displays the names of the next 20 location areas",
callback: commandMap,
}
var mapBackCommand = cliCommand{
name: "mapb",
description: "Displays the names of the previous 20 location areas",
callback: commandMapBack,
}
c := &context{
commands: map[string]cliCommand{},
commands: map[string]cliCommand{},
client: pokeapi.NewClient(pokecache.NewCache(5 * time.Second)),
prevOffset: 0,
nextOffset: 0,
}
c.register(exitCommand)
c.register(helpCommand)
c.register(mapCommand)
c.register(mapBackCommand)
return c
}
@@ -73,3 +97,44 @@ func commandHelp(c *context) error {
return nil
}
func getMaps(c *context, offset int) error {
page, err := c.client.Locations.Get(offset)
if err != nil {
fmt.Println("Unable to get locations")
return err
}
c.prevOffset = page.GetPreviousOffset()
c.nextOffset = page.GetNextOffset()
if len(page.Results) == 0 {
fmt.Println("No locations found")
} else {
locationsPerPage := 20
currentPage := (offset / locationsPerPage) + 1
totalPages := page.Count / locationsPerPage
fmt.Printf("Displaying page %d of %d page(s)\n", currentPage, totalPages)
}
for _, location := range page.Results {
fmt.Printf("%s\n", location.Name)
}
return nil
}
func commandMap(c *context) error {
return getMaps(c, c.nextOffset)
}
func commandMapBack(c *context) error {
if c.prevOffset == 0 && (c.nextOffset == 0 || c.nextOffset == 20) {
fmt.Println("You're on the first page")
return nil
}
return getMaps(c, c.prevOffset)
}