This commit is contained in:
2025-03-10 22:20:51 +02:00
parent 0148583f5b
commit cd8c2ee09e
6 changed files with 156 additions and 12 deletions

View File

@@ -1,18 +1,21 @@
package pokeapi
import (
"github.com/rdarius/boot-dev-pokedex/pokecache"
"net/http"
"time"
)
// Client -
type Client struct {
cache pokecache.Cache
httpClient http.Client
}
// NewClient -
func NewClient(timeout time.Duration) Client {
func NewClient(timeout, cacheInterval time.Duration) Client {
return Client{
cache: pokecache.NewCache(cacheInterval),
httpClient: http.Client{
Timeout: timeout,
},

View File

@@ -13,6 +13,16 @@ func (c *Client) ListLocations(pageURL *string) (RespShallowLocations, error) {
url = *pageURL
}
if val, ok := c.cache.Get(url); ok {
locationsResp := RespShallowLocations{}
err := json.Unmarshal(val, &locationsResp)
if err != nil {
return RespShallowLocations{}, err
}
return locationsResp, nil
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return RespShallowLocations{}, err
@@ -22,7 +32,6 @@ func (c *Client) ListLocations(pageURL *string) (RespShallowLocations, error) {
if err != nil {
return RespShallowLocations{}, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
@@ -38,5 +47,6 @@ func (c *Client) ListLocations(pageURL *string) (RespShallowLocations, error) {
return RespShallowLocations{}, err
}
c.cache.Add(url, dat)
return locationsResp, nil
}