This commit is contained in:
2025-03-10 22:14:46 +02:00
parent bea73f0115
commit 0148583f5b
5 changed files with 144 additions and 6 deletions

71
main.go
View File

@@ -2,20 +2,35 @@ package main
import (
"bufio"
"errors"
"fmt"
"github.com/rdarius/boot-dev-pokedex/pokeapi"
"os"
"strings"
"time"
)
type config struct {
pokeapiClient pokeapi.Client
nextLocationsURL *string
prevLocationsURL *string
}
type cliCommand struct {
name string
description string
callback func() error
callback func(*config) error
}
var commands map[string]cliCommand
func main() {
pokeClient := pokeapi.NewClient(5 * time.Second)
cfg := &config{
pokeapiClient: pokeClient,
}
commands = map[string]cliCommand{
"exit": {
name: "exit",
@@ -27,6 +42,16 @@ func main() {
description: "Display a help message",
callback: printHelpMessage,
},
"map": {
name: "map",
description: "Get the next page of locations",
callback: commandMapf,
},
"mapb": {
name: "mapb",
description: "Get the previous page of locations",
callback: commandMapb,
},
}
for {
// read user input
@@ -40,7 +65,7 @@ func main() {
//check if command is in commands map
cmd, ok := commands[command]
if ok {
err := cmd.callback()
err := cmd.callback(cfg)
if err != nil {
fmt.Println(err)
}
@@ -52,7 +77,7 @@ func main() {
}
}
func commandExit() error {
func commandExit(*config) error {
fmt.Println("Closing the Pokedex... Goodbye!")
os.Exit(0)
return nil
@@ -70,10 +95,44 @@ func cleanInput(text string) []string {
return separated
}
func printHelpMessage() error {
func printHelpMessage(*config) error {
fmt.Print("Welcome to the Pokedex!\nUsage:\n\n")
for k, v := range commands {
fmt.Printf("%s: %s\n", k, v.description)
for _, v := range commands {
fmt.Printf("%s: %s\n", v.name, v.description)
}
return nil
}
func commandMapf(cfg *config) error {
locationsResp, err := cfg.pokeapiClient.ListLocations(cfg.nextLocationsURL)
if err != nil {
return err
}
cfg.nextLocationsURL = locationsResp.Next
cfg.prevLocationsURL = locationsResp.Previous
for _, loc := range locationsResp.Results {
fmt.Println(loc.Name)
}
return nil
}
func commandMapb(cfg *config) error {
if cfg.prevLocationsURL == nil {
return errors.New("you're on the first page")
}
locationResp, err := cfg.pokeapiClient.ListLocations(cfg.prevLocationsURL)
if err != nil {
return err
}
cfg.nextLocationsURL = locationResp.Next
cfg.prevLocationsURL = locationResp.Previous
for _, loc := range locationResp.Results {
fmt.Println(loc.Name)
}
return nil
}