Skip to content

Commit

Permalink
Add caching to ListLocationArea method
Browse files Browse the repository at this point in the history
  • Loading branch information
jurichar committed Mar 15, 2024
1 parent 2fa7269 commit 6696502
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
16 changes: 15 additions & 1 deletion internal/pokeapi/location_area_req.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ func (c *Client) ListLocationArea(pageURL *string) (LocationAreasResp, error) {
fullUrl = *pageURL
}

dat, ok := c.cache.Get(fullUrl)
if ok {
fmt.Println("cache hit!")
locationAreasResp := LocationAreasResp{}
err := json.Unmarshal(dat, &locationAreasResp)
if err != nil {
return LocationAreasResp{}, err
}
return locationAreasResp, nil
}
fmt.Println("cache miss!")

req, err := http.NewRequest("GET", fullUrl, nil)
if err != nil {
return LocationAreasResp{}, err
Expand All @@ -29,7 +41,7 @@ func (c *Client) ListLocationArea(pageURL *string) (LocationAreasResp, error) {
return LocationAreasResp{}, fmt.Errorf("bad status code: %v", resp.StatusCode)
}

dat, err := io.ReadAll(resp.Body)
dat, err = io.ReadAll(resp.Body)
if err != nil {
return LocationAreasResp{}, err
}
Expand All @@ -40,5 +52,7 @@ func (c *Client) ListLocationArea(pageURL *string) (LocationAreasResp, error) {
return LocationAreasResp{}, err
}

c.cache.Add(fullUrl, dat)

return locationAreasResp, nil
}
6 changes: 5 additions & 1 deletion internal/pokeapi/pokeapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,20 @@ package pokeapi
import (
"net/http"
"time"

"github.com/jurichar/pokedexcli/internal/pokecache"
)

const baseURL = "https://pokeapi.co/api/v2/"

type Client struct {
cache pokecache.Cache
httpClient http.Client
}

func NewClient() Client {
func NewClient(cacheInterval time.Duration) Client {
return Client{
cache: pokecache.NewCache(cacheInterval),
httpClient: http.Client{
Timeout: time.Minute,
},
Expand Down
8 changes: 6 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package main

import "github.com/jurichar/pokedexcli/internal/pokeapi"
import (
"time"

"github.com/jurichar/pokedexcli/internal/pokeapi"
)

type config struct {
pokeapiClient pokeapi.Client
Expand All @@ -11,7 +15,7 @@ type config struct {
func main() {

cfg := config{
pokeapiClient: pokeapi.NewClient(),
pokeapiClient: pokeapi.NewClient(time.Hour),
}
startRepl(&cfg)
}

0 comments on commit 6696502

Please sign in to comment.